stored procedure in sql used in c# - c#

I have used following stored procedure in sql:
alter procedure [dbo].[usp_Member_Org_OnGoingJobs]
(
#idUser varchar(50)
)
as
begin
declare #qry as varchar(max)
set #qry='select J.idJob,j.DateAdded,j.OpenedByWho,j.JobAddress ,j.final,j.idOrg,j.note
from Job J
inner join Users U on
U.idOrg=J.idOrg
where U.IdUser='+ #idUser+ '
and ISNULL(j.Final,'')=''
order by idJob'
execute(#qry)
end
GO
This stored procedure is formed sucessfully in sql.
But, When i tried to use them through asp.net c#, It gives me error:
Incorrect syntax near the keyword 'order'.
Everything seems correct.
Please tell me where i am making mistake??
Edit:
private void BindOnGoingJobs()
{
string sqlOnGoingJobs = "usp_Member_Org_OnGoingJobs";
DataTable dtJobList = new DataTable();
ArrayList paramList = new ArrayList();
paramList.Add(new ParamData("#idUser", Convert.ToString(Session["idUser"])));
dtJobList = obj.ExecuteProcedureAndGetDataTable(sqlOnGoingJobs, paramList);
grdOnGoingJobs.DataSource = dtJobList;
grdOnGoingJobs.DataBind();
paramList.Clear();
}
public DataTable ExecuteProcedureAndGetDataTable(string procedureName, ArrayList Parameters)
{
DataTable dt = new DataTable();
try
{
if (con.State != ConnectionState.Open)
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procedureName;
cmd.Parameters.Clear();
foreach (ParamData p in Parameters)
{
cmd.Parameters.AddWithValue(p.pName, p.pValue);
}
da.SelectCommand = cmd;
da.Fill(dt);
con.Close();
return dt;
}
catch (Exception ex)
{
con.Close();
return dt;
}
}

You need to double your single quotes around the ISNULL check
set #qry='select J.idJob,j.DateAdded,j.OpenedByWho,j.JobAddress ,j.final,j.idOrg,j.note
from Job J
inner join Users U on
U.idOrg=J.idOrg
where U.IdUser='+ #idUser+ '
and ISNULL(j.Final,'''')=''''
order by idJob'

You need to escape the quotation mark by placing quotes 2 times like this.
and ISNULL(j.Final,'''')=''''
Check this blog post http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/

Just add the table alias in order by, I guess should solve the issue
order by J.idJob

Related

How to get values from table valued function in C#

I have a program where i have to display
The Event Description (OpisDogodka)
Location (Lokacija)
Time (ura)
My table valued function:
[dbo].[DobiDogodek](
#Ime nvarchar(100), #Datum date)
RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=#Ime AND Datum=#Datum)
My method to connect to the server:
public string Dobi_dogodek(string ime,string datum)
{
string a="";
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", datum); //how to pass date only?
try
{
SqlDataReader Reader = cmd.ExecuteReader();
while(Reader.Read())
{
a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return a;
}
I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?
4.6.2017 (11.40 am CET)Update:
It seems I get the desired result
public List<string> Dobi_dogodek(string ime,string datum)
{
s = new List<string>();
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
try
{
foreach (DataRow dr in dt.Rows)
{
s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return s;
}
Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?
Try this:
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
See also https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx .
what is happening when you run it? are you getting an error message? is it getting it as an int? did you see what the sql server is getting from application by using sql profiler?
I will double check but I think your problem is you are not putting quotes around your variables in our statement so when it runs it is evaluating them as ints. try "SELECT * FROM dbo.DobiDogodek('#Ime','#Datum')". It been a long time since I havnt used something like EF...

How to pass an array Oracle parameter in c#

I have a problem passing an array parameter using c#, my code is:
private OracleDataAdapter da;
private OracleConnection cnn;
public DataTable select_ids_between_friends(int cod, List<int> excludeList) {
DataTable dt = new DataTable();
try
{
using (cnn = new OracleConnection(Properties.Settings.Default.connectionString1))
{
cnn.Open();
da = new OracleDataAdapter("PROC_SELECT_IDS_BT_FRIENDS", cnn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("CURSOR", OracleDbType.RefCursor, ParameterDirection.Output);
da.SelectCommand.Parameters.Add("COD_US", OracleDbType.Int32, cod, ParameterDirection.Input);
da.SelectCommand.Parameters.Add(new OracleParameter("IDS_FRIEND", OracleDbType.Int32));
da.SelectCommand.Parameters[2].CollectionType = OracleCollectionType.PLSQLAssociativeArray;
da.SelectCommand.Parameters[2].Value = excludeList.ToArray();
da.SelectCommand.Parameters[2].Size = excludeList.Count;
da.Fill(dt);
cnn.Close();
}
}
catch (Exception ex)
{
}
return dt;
}
in the database I created the array and the stored procedure like this:
This is the Oracle type:
CREATE TYPE FACEBOOK.ARRAY_ID_FRIENDS AS TABLE OF INT;
Finally this is my procedure:
CREATE OR REPLACE PROCEDURE PROC_SELECT_IDS_BT_FRIENDS
(DATA_CURSOR OUT SYS_REFCURSOR,COD_US IN INT, IDS_FRIEND IN FACEBOOK.ARRAY_ID_FRIENDS) IS
BEGIN
OPEN DATA_CURSOR FOR
SELECT ID_USER1,ID_USER2 FROM T_FRIENDSHIP WHERE ID_USER2 NOT IN(SELECT COLUMN_VALUE FROM TABLE(IDS_FRIEND)))
END;
/
The error showed is PLS-00306: wrong number or types of arguments in call PROC_SELECT_IDS_BT_FRIENDS. Please help me. Thanks in advance.
This line:
da.SelectCommand.Parameters.Add(new OracleParameter("IDS_FRIEND", OracleDbType.Int32));
Why is it an Int32? Shouldn't it be an array? I see that you declare it as an array, but only till later. Is there a different way to declare it?

Cannot find table 0 in dataset using stored procedures

I am not getting filled dataset after executing a stored procedure.
protected void btnsub_Click(object sender, EventArgs e)
{
ArrayList arInsert = ReturnParameter_insert();
DataSet dsInsertProfile = objadmin.GetGridData(arInsert, objconstant.sSP_INSERT_PROFILE);
if(int.Parse(dsInsertProfile.Tables[0].Rows[0].ItemArray[0].ToString())== 0)
{
lblThank.Text = "Your profile have been successfully saved.";
}
else
{
lblThank.Text = "Your profile is not saved, please try again later.";
}
}
public ArrayList ReturnParameter_insert()
{
ArrayList arProfile = new ArrayList();
Object[] c_first_name = new object[3] { "#strFname", "Varchar", (txtfname.Text != "") ? txtfname.Text : "" };
arProfile.Add(c_first_name);
return arProfile;
}
public DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
dsDataSet = datamanager.GetGridData(dbArray, sSpName);
return dsDataSet;
}
public static SqlDbType GetSqlDataType(string sDataType)
{
return (sDataType == "Integer") ? SqlDbType.Int : (sDataType == "Varchar") ? SqlDbType.VarChar : (sDataType == "Date") ? SqlDbType.Date : SqlDbType.BigInt;
}
public static DataSet GetGridData(ArrayList dbArray, string sSpName)
{
DataSet dsDataSet = new DataSet();
SqlConnection cn = createConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sSpName;
object objPrMtrName;
object objSqlType;
object objPrMtrVal;
int i;
for (i = 0; i < dbArray.Count; i++)
{
objPrMtrName = ((object[])(dbArray[i]))[0];
objSqlType = ((object[])(dbArray[i]))[1];
objPrMtrVal = ((object[])(dbArray[i]))[2];
cmd.Parameters.Add(objPrMtrName.ToString(), GetSqlDataType(objSqlType.ToString())).Value = objPrMtrVal;
}
cmd.Connection = cn;
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
return dsDataSet;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cn.Close();
cn.Dispose();
}
}
My stored procedure:
CREATE Procedure spInsert_profile
(#strFname varchar(200))
AS
BEGIN
INSERT INTO gdt_Users([c_first_name], [d_modified_dttm], [d_created_dttm])
VALUES(#strFname, GETDATE(), GETDATE())
END
Here I am using 3 tier, the same methods are working successfully for other pages but not for this particular code. The dataset in GETGRIDDATA method is filling null value. I am not able to find. Please help me....
you performing insert operation in your procedure than how is going to return to data Insert into statement does insert operation not retrieve operation.
...To retrieve data you need to call procedure with select * statement.
There is no select statement in your stored proc. adapter.fill() should recieve some sort of table from the stored proc's output.
From what I can see here you are executing a stored procedure that only performs an INSERT command, The reason you are getting a NULL value back is because a non query command such as UPDATE or INSERT will generally return only the number of rows affected e.g. 1 and not the data of the table you inserted to.
You would need to perform a SELECT command after the insert to get any data back.
The problem is in your stored procedure... you have to add select statement to the stored procedure for your return result in DataSet
Because you use Insert Into in your stored procedure.
Access based on Tables property:
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dsDataSet);
var table1 = dsDataSet.Tables[0];
var table2 = dsDataSet.Tables[1];
Link : http://msdn.microsoft.com/fr-fr/library/system.data.dataset.tables.aspx

Dependent Dropdown list. Filtering from one list to another

I having an issue passing the return parameters to the second dropdown list. Second list is completely dependent on the selection from the first one. I'm pretty sure the SP is fine. Again, my issue is passing the value.
Stored Procedure
PROCEDURE ev_dropdown(
cur_out IN OUT eqpack.t_cur_out,
p_result OUT VARCHAR2,
p_reference_id IN NUMBER
)
IS
BEGIN
OPEN cur_out FOR
SELECT ev_id, ev
FROM event WHERE a_ref = p_reference_id;
EXCEPTION
WHEN OTHERS
THEN
p_result :=
'An error occurred in get_events_dropdown - ' || SQLERRM;
END ev_dropdown;
.cs
public void populateSpecificEv(int p)
{
DataTable dtRef = CreateReferenceDT();
string conn = GetConnectString();
using (OracleConnection connection = new OracleConnection(conn))
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = "eqpackage.get_events_dropdown";
command.CommandType = CommandType.StoredProcedure;
command.Parameters["p_reference_id"].Value = p;
OracleDataReader reader;
reader = command.ExecuteReader();
dtRef.Rows.Add("0", "-select-");
while (reader.Read())
{
dtRef.Rows.Add(reader[0], reader[1]);
}
connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
command.Connection.Dispose();
return dtRef; //Error -returns void, a return keyword must not be followed by an object expression
}
}
DataTable CreateReferenceDT()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
return dt;
}
aspx.cs
protected void ddlSys_SelectedIndexChanged1(object sender, EventArgs e)
{
int p = int.Parse(ddlSystems.SelectedItem.Value);
dbase.populateSpecificEvent(p);
DataTable dt1 = dbase.PopulateEvDropDown();
ddlEv.DataSource = dt1;
ddlEv.DataTextField = "name";
ddlEv.DataValueField = "id";
ddlEv.DataBind();
}
I believe you want to update your stored procedure to actually just perform a SELECT statement without explicitly creating its own cursor. You would then call command.ExecuteQuery() (which I see you are doing), which would return an IDataReader, which is basically a forward-only, read-only cursor.
I would remove the following extra lines:
connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
command.Connection.Dispose();
If you change your stored procedure to actually just be a select statement, then you can use your while(reader.Read()) loop to read in the rows, one at a time, and insert them into your DataTable, or simply call DataTable.Load(IDataReader).

Stored procedure not updating data

I'm trying to pass a data table to a stored procedure. The table has four columns, OldDifficulty, OldIndex, NewDifficulty, and NewIndex. It is passed to a stored procedure which is supposed to update all the rows in a Puzzles table changing rows with the old index and difficulty to their new index and difficulty. The Puzzles table does not change, and I can't figure out why. I'm not sure whether the problem is in the code or in the database query.
Here is the C# code that calls the stored procedure:
var Form = context.Request.Form;
DataTable table = new DataTable();
table.Columns.Add("OldDifficulty");
table.Columns.Add("OldIndex");
table.Columns.Add("NewDifficulty");
table.Columns.Add("NewIndex");
foreach (var key in Form.Keys)
{
var Old = key.ToString().Split('_');
var New = Form[key.ToString()].Split('_');
if (Old == New || New.Length == 1 || Old.Length == 1) continue;
table.Rows.Add(Old[0], int.Parse(Old[1]), New[0], int.Parse(New[1]));
}
using (var con = new SqlConnection(SqlHelper.ConnectionString))
{
con.Open();
using (var com = new SqlCommand("RearrangePuzzles", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
com.ExecuteNonQuery();
}
con.Close();
}
and here is the stored procedure:
ALTER PROCEDURE [dbo].[RearrangePuzzles]
#ChangedPuzzles ChangedPuzzlesTable READONLY
AS
UPDATE p
SET
NthPuzzle = cp.NewIndex,
Difficulty = cp.NewDifficulty
FROM
Puzzles p JOIN
#ChangedPuzzles cp ON cp.OldIndex = p.NthPuzzle AND cp.OldDifficulty = p.Difficulty
Do you have any idea why the table isn't updating? Is there something wrong with my SQL?
Everything looks ok, except:
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
I would change to:
com.Parameters.Add(new SqlParameter("#ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
# sign - prefix in parameter name.
Use SQL Server Profiler to see whether this query actually is executed.
check the order of fields in the table type ChangedPuzzlesTable , it must be same as datatable any change in order may cause this problem
check error by adding a try catch
try
{
using (var con = new SqlConnection(SqlHelper.ConnectionString))
{
con.Open();
using (var com = new SqlCommand("RearrangePuzzles", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
com.ExecuteNonQuery();
}
con.Close();
}
}
catch (Exception ex)
{
// ex will show you the error
}

Categories