SQLParameter not working properly - c#

I am trying to access a stored procedure and I'm getting an error that says:
Procedure or function 'getbug' expects parameter '#bugID', which was not supplied.
This is my code to call the procedure.
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.Parameters.Add(new SqlParameter("bugID", bugID));
bugID is set as 1089 (and is type int)
I can't figure out why this won't work.

Try this instead
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#bugID", bugID));

Try adding the "#" to the parameter
SqlCommand cmd = new SqlCommand("getbug", cn);
cmd.Parameters.Add(new SqlParameter("#bugID", bugID));

More code will help. Here's a couple of ideas though.
If you're calling a stored procedure, you need to specify the CommandType. Also, you can use the AddWithValue method to shorten your code.
using (var cn = new SqlConnection("your connection string"))
{
using (var cmd = new SqlCommand("getbug", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#bugID", bugID);
//etc...
}
}

Related

Session variable as a SqlParameter

I've got this all except for my...
cmd.Parameters["#CAssetID"].Value.ToString();
Line of code where I am trying to assign the session variable to SqlParameter to pass it in to a stored procedure. I just can't seem to get the syntax right. I've tried several different things here is my last attempt.
SqlConnection RejectConnecton = new SqlConnection("Data Source=GBAPTCCSR01;Initial Catalog=CInTracDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "usp_RejectSubmission";
cmd.Parameters["#CAssetID"].Value.ToString();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = RejectConnecton;
RejectConnecton.Open();
reader = cmd.ExecuteReader();
RejectConnecton.Close();
Thanks for any help you can offer!
cmd.Parameters.AddWithValue("#CAssetID", Session["YourSessionParamName"]);

How retrieve the output parameter from stored procedure from a DataManager [duplicate]

My stored procedure has an output parameter:
#ID INT OUT
How can I retrieve this using ado.net?
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["#ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["#Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from #Walter Stabosz and #Stephen Kennedy and to match the update code edit in the question from #abatishchev.
For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
SqlParameter outputParam = cmd.Parameters.Add("#ID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
conn.Open();
using(IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
//read in data
}
}
// reader is closed/disposed after exiting the using statement
int id = outputParam.Value;
}
Not my code, but a good example i think
source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
using System;
using System.Data;
using System.Data.SqlClient;
class OutputParams
{
[STAThread]
static void Main(string[] args)
{
using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
{
SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
cmd.CommandType=CommandType.StoredProcedure ;
SqlParameter parm= new SqlParameter("#CustomerID",SqlDbType.NChar) ;
parm.Value="ALFKI";
parm.Direction =ParameterDirection.Input ;
cmd.Parameters.Add(parm);
SqlParameter parm2= new SqlParameter("#ProductName",SqlDbType.VarChar);
parm2.Size=50;
parm2.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm2);
SqlParameter parm3=new SqlParameter("#Quantity",SqlDbType.Int);
parm3.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm3);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(cmd.Parameters["#ProductName"].Value);
Console.WriteLine(cmd.Parameters["#Quantity"].Value.ToString());
Console.ReadLine();
}
}
public static class SqlParameterExtensions
{
public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)
{
if (sqlParameter.Value == DBNull.Value
|| sqlParameter.Value == null)
{
if (typeof(T).IsValueType)
return (T)Activator.CreateInstance(typeof(T));
return (default(T));
}
return (T)sqlParameter.Value;
}
}
// Usage
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("storedProcedure", conn))
{
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
int result = outputIdParam.GetValueOrDefault<int>();
}
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“#Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“#Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“#Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “#EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
You can get your result by below code::
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add other parameters parameters
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#Id";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
conn.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string Id = outPutParameter.Value.ToString();
// *** read output parameter here, how?
conn.Close();
}
Create the SqlParamObject which would give you control to access methods on the parameters
:
SqlParameter param = new SqlParameter();
SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)
: param.ParameterName = "#yourParamterName";
Clear the value holder to hold you output data
: param.Value = 0;
Set the Direction of your Choice (In your case it should be Output)
: param.Direction = System.Data.ParameterDirection.Output;
That looks more explicit for me:
int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;

Stored procedure is not working and getting stopped

I m running a piece of code for scheduler in my project. But it is not working as expected.
private void Initiate_User(string strEmpCard)
{
//conn.Open();
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString() + "", conn);
ObjPriCmd.ExecuteNonQuery();
}
The debugger stops and opens a form after my ExecuteNonQuery() line is debugged. I am not able to trace the error also. what is wrong here ??
UPDATE
My error query
insert into p_emp_clearance_hdr
(Emp_mkey,
Emp_card_no,
RA_1,
RA_2,
Depatment,
Sub_Department,
Date_of_Joining,
Resignation_date,
Last_Working_Days,
UserId)
select
em.mkey,
em.emp_card_no,
em.Reporting_To,
em.Reporting_To2,
em.Department_mkey,
em.SubDept_mkey,
convert(varchar(10), em.resig_date, 103) resig_date,
convert( varchar(10), em.Dt_Of_Join, 103) Dt_Of_Join,
convert(varchar(10), em.Dt_of_leave, 103) Dt_of_leave,
um.mkey
from emp_mst em join user_mst um
on em.mkey = um.Employee_mkey
where em.mkey = #emp_mkey
As you explained in comments, you are getting error:
ExecuteNonQuery: Connection property has not been initialized.
It means you have not initialized the connection. You have just declared it:
SqlConnection conn;
You should do like:
conn = new SqlConnection(#"you connection string");
//then your code
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString(), conn);
ObjPriCmd.ExecuteNonQuery();
The best practice:
You should use a SqlCommand property CommandType to define that you're calling a StoredProcedure when calling from C#. And define parameters using SqlCommand .Parameters.Add it handles the SqlInjection issues itself.
conn = new SqlConnection(#"you connection string");
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// parameter name , parameter type parameter value
cmd.Parameters.Add("#parameter name", SqlDbType.VarChar).Value = strEmpCard.ToString();
con.Open();
cmd.ExecuteNonQuery();
}
You can Try it with USing Statement:-
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Parameter Name", Type).Value = "Value of Parameter";
conn.Open();
cmd.ExecuteNonQuery();
}

Update Command with stored procedure

I have an update query(stored procedure) which is working properly in SQL Server when I execute it.
CREATE PROCEDURE updatestudenthws(#stdid nvarchar(50),#hwid int, #grade float)
AS
UPDATE Table_Exercise_Answer
SET
ExAns_Grade = #grade
WHERE ExAns_Exercise = #hwid AND ExAns_Student = #stdid
but when I run the program it does not have any effect in my table and also I don't have any error.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.VarChar);
cmd.Parameters.Add("#stdid", SqlDbType.VarChar);
cmd.Parameters.Add("#grade", SqlDbType.VarChar);
cmd.Parameters["#hwid"].Value = hwid;
cmd.Parameters["#stdid"].Value = studentid;
cmd.Parameters["#grade"].Value = grade;
cmd.ExecuteNonQuery();
con.Close();
What is my mistake?
How should I do this work?
Use AddWithValue(), so you don't have to provide the type, which allowed you to make the mistake of passing varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Your ADO.NET code defining the parameters for the stored procedure is wrong in that you don't define the parameters with their proper datatypes.
Your stored procedure defines:
#stdid nvarchar(50) --> but you define it as varchar
#hwid int --> but you define it as varchar
#grade float --> but you define it as varchar
You need to change your code to this:
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.Int); // this needs to be SqlDbType.Int
cmd.Parameters.Add("#stdid", SqlDbType.NVarChar, 50); // this should be SqlDbType.NVarChar and specify its proper length
cmd.Parameters.Add("#grade", SqlDbType.Float); // this needs to be SqlDbType.Float
when you use AddWithValue(), don't you have to provide the type passing like varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();

Get output parameter value in ADO.NET

My stored procedure has an output parameter:
#ID INT OUT
How can I retrieve this using ado.net?
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.
Using your code sample:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["#ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["#Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).
EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from #Walter Stabosz and #Stephen Kennedy and to match the update code edit in the question from #abatishchev.
For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.
using (SqlConnection conn = new SqlConnection())
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
SqlParameter outputParam = cmd.Parameters.Add("#ID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
conn.Open();
using(IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
//read in data
}
}
// reader is closed/disposed after exiting the using statement
int id = outputParam.Value;
}
Not my code, but a good example i think
source: http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
using System;
using System.Data;
using System.Data.SqlClient;
class OutputParams
{
[STAThread]
static void Main(string[] args)
{
using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
{
SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
cmd.CommandType=CommandType.StoredProcedure ;
SqlParameter parm= new SqlParameter("#CustomerID",SqlDbType.NChar) ;
parm.Value="ALFKI";
parm.Direction =ParameterDirection.Input ;
cmd.Parameters.Add(parm);
SqlParameter parm2= new SqlParameter("#ProductName",SqlDbType.VarChar);
parm2.Size=50;
parm2.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm2);
SqlParameter parm3=new SqlParameter("#Quantity",SqlDbType.Int);
parm3.Direction=ParameterDirection.Output;
cmd.Parameters.Add(parm3);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(cmd.Parameters["#ProductName"].Value);
Console.WriteLine(cmd.Parameters["#Quantity"].Value.ToString());
Console.ReadLine();
}
}
public static class SqlParameterExtensions
{
public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)
{
if (sqlParameter.Value == DBNull.Value
|| sqlParameter.Value == null)
{
if (typeof(T).IsValueType)
return (T)Activator.CreateInstance(typeof(T));
return (default(T));
}
return (T)sqlParameter.Value;
}
}
// Usage
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("storedProcedure", conn))
{
SqlParameter outputIdParam = new SqlParameter("#ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
int result = outputIdParam.GetValueOrDefault<int>();
}
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“#Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“#Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“#Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “#EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
You can get your result by below code::
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add other parameters parameters
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#Id";
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
conn.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string Id = outPutParameter.Value.ToString();
// *** read output parameter here, how?
conn.Close();
}
Create the SqlParamObject which would give you control to access methods on the parameters
:
SqlParameter param = new SqlParameter();
SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)
: param.ParameterName = "#yourParamterName";
Clear the value holder to hold you output data
: param.Value = 0;
Set the Direction of your Choice (In your case it should be Output)
: param.Direction = System.Data.ParameterDirection.Output;
That looks more explicit for me:
int? id = outputIdParam.Value is DbNull ? default(int?) : outputIdParam.Value;

Categories

Resources