Another SQL parameter - UPDATE statement - c#

I'm not seeing why my update statement isn't actually updating. Here is what I have:
private void submit_button_Click(object sender, EventArgs e)
{
string insert = insertbox.Text;
SqlParameter param2 = new SqlParameter("#param2", SqlDbType.Text);
param2.Value = insert;
var connlink = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\MSSQL\\Data\\Inserts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
var cmd1 = new SqlCommand(#"SELECT qty_onhand FROM [insert] WHERE (Name LIKE #param2)", connlink);
connlink.Open();
cmd1.Parameters.Add(param2);
var onhand = Convert.ToInt16(cmd1.ExecuteScalar());
// The param2 in the statement passes fine and returns the value into "onhand".
// Below, the parameters don't seem to be passed. There is no error but the record isn't updated.
int new_onhand = Convert.ToInt16(qtybox1.Text);
Convert.ToInt16(onhand);
new_onhand = onhand - new_onhand;
SqlParameter param1 = new SqlParameter("#param1", SqlDbType.SmallInt);
param1.Value = new_onhand;
SqlParameter param3 = new SqlParameter("#param3", SqlDbType.Text);
param3.Value = param2.ToString();
var cmd = new SqlCommand(#"UPDATE [insert] SET qty_onhand = #param1 WHERE (Name LIKE #param3)", connlink);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param3);
cmd.ExecuteNonQuery();
connlink.Close();
}
I'm not sure of the difference of why one works and the other doesn't.

you set the value of param3 by calling ToString on param2: param3.Value = param2.ToString();
Calling ToString on a SqlParameter returns the parameter name. In our case, it returns "#param2" as a string, and not the value of it. Try using param2.Value.
Or actually to insert, since you wrote param2.Value = insert;.

The lines below looks incorrect to me because param2 is of type SqlParameter and you using param2.ToString() as value for param3.value
SqlParameter param3 = new SqlParameter("#param3", SqlDbType.Text);
**param3.Value = param2.ToString();**

Related

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;

C# SQL Command parameter not working

I've done some trouble shooting by taking out the parameters and replacing them with text, and the only parameter that is not working is #seat and I can't figure out why.
allSeats is an array of custom controls. I've tried replacing the parameter contents with an actual string ie. "A1" and that still doesn't work. If I remove the #seat parameter and replace it with A1, it works, but I need to be able to set the column name dynamically.
myConnection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE Events SET #seat = #truefalse WHERE Name = #name", myConnection);
SqlParameter param = new SqlParameter();
SqlParameter param2 = new SqlParameter();
SqlParameter param3 = new SqlParameter();
param.ParameterName = "#seat";
param2.ParameterName = "#truefalse";
param2.DbType = System.Data.DbType.Boolean;
param3.ParameterName = "#name";
param.Value = allSeats[i].Name;
param2.Value = allSeats[i].taken;
param3.Value = name;
myCommand.Parameters.Add(param);
myCommand.Parameters.Add(param2);
myCommand.Parameters.Add(param3);
myCommand.ExecuteNonQuery();
Any help is appreciated. If I need to post more relevant code please let me know and I shall add it.
In your
SET #seat = #truefalse
part, you try to parameterize your column name. You can't do that. You only can parameterize your values, not column name or table names.
You can use dynamic SQL for such a case but it is not recommended. Read
The Curse and Blessings of Dynamic SQL
SELECT * FROM #tablename
As a recommendation, use a white list such a case. I hope, there can only be a fixed set of possible correct values for the column name. Of course, this requires strong validation in your inputs part.
Agree with Soner. Change the string before you create the command
string cmdStr = string.Format("UPDATE Events SET {0} = #truefalse WHERE Name = #name", allSeats[i].Name)
Then
only use 2 parameters.
SqlCommand myCommand = new SqlCommand(cmdStr, myConnection);
SqlParameter param = new SqlParameter();
SqlParameter param2 = new SqlParameter();
etc.
cmd.parameter.addwithvalue("#param1", value1);
cmd.parameter.addwithvalue("#param2", value2);
use like this.
As Soner has mentioned, columns cannot be parameterized. This means you will either have to create dynamic queries, or create all the parameterized once at the startup, one query per column name.
this can be done in the following example:
private static Dictionary<string, SqlCommand> parameterizedCommands = new Dictionary<string,SqlCommand>();
public static void CreateparameterizedCommandsy(string[] colums)
{
parameterizedCommands = new Dictionary<string,SqlCommand>();
foreach (string colname in colums)
{
parameterizedCommands.Add(colname, CreateCommandForColumn(colname));
}
}
public static SqlCommand CreateCommandForColumn(string columnName)
{
SqlCommand myCommand = new SqlCommand(string.Format("UPDATE Events SET {0} = #truefalse WHERE Name = #name",columnName));
// the following statement creates the parameter in one go. Bit = boolean
myCommand.Parameters.Add("#truefalse", SqlDbType.Bit);
myCommand.Parameters.Add("#name", SqlDbType.Text);
return myCommand;
}
public int ExccuteColumnUpdate(string columnName, bool setToValue, string name, SqlConnection connection)
{
connection.Open();
try
{
SqlCommand command;
if (parameterizedCommands.TryGetValue(columnName, out command))
{
command.Connection = connection;
command.Parameters["#truefalse"].Value = setToValue;
command.Parameters["#name"].Value = name;
return command.ExecuteNonQuery();
}
}
finally
{
connection.Close();
}
return 0;
}

Adding more number of parameters to sqlparameter class

I have to call a stored procedure but i am having more number of parameters is there any simple way to do this? or simply adding every parameter to sqlparameter class?? like below
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
Be aware that Paramters.Add has an overload that takes in a string and a DbType, so you don't have to call the Parameter constructor. You could replace the line you are currently using to add a new parameter:
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar)).Value = TextBox1.Text;
with the following shorter (but functionally equivalent) line:
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
If you want to add more parameters, you would simply add them to the Parameters property of your command, like so:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
Aside from that, have you tried using Parameters.AddWithValue? You can use this if the data type of your column maps to the type of your value in C#. You can find a mapping of C# to SQL Server data typse here.
You would use it like so:
// Assume your sproc has a parameter named #Age that is a SqlInt32 type
int age = 5;
// Since age is a C# int (Int32), AddWithValue will automatically set
// the DbType of our new paramter to SqlInt32.
command.Parameters.AddWithValue("#Age", 5);
If you need to specify the SqlDbType, AddWithValue returns the parameter you just added, so it's as simple as adding an extra statement to set the DbType property at the end, although at this point, you're better off just using the original .Add function and setting the value.
command.Parameters.AddWithValue("#Firstname", TextBox1.Text).DbType = SqlDbType.NVarChar;
Use Array of type SqlParameter and insert that into SqlCommand
SqlCommand Comm = new SqlCommand("Command text", new SqlConnection("Connection String");
SqlParameter[] param = {new SqlParameter("#Name","Value"),
new SqlParameter("#Name","Value"),
........
};
Comm.Parameters.AddRange(param);
Just call the command.Parameters.Add method multiple times:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar, 100).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar, 100).Value = TextBox2.Text;
command.Parameters.Add("#City", SqlDbType.NVarChar, 100).Value = TextBox3.Text;
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox4.Text);
....... and so on .....
You may use like it
return new SqlParameter[]
{
new SqlParameter("#Firstname", SqlDbType.VarChar)
{
Value = Firstname.Text
},
new SqlParameter("#Lastname", SqlDbType.VarChar)
{
Value = Lastname.Text
},
};
You can use dapper-dot-net
sample code:
var dog = connection.Query<Dog>("select Age = #Age, Id = #Id", new { Age = (int?)null, Id = guid });
Insert example:
connection.Execute(#"insert MyTable(colA, colB) values (#a, #b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"
The command.Parameters.Add is deprecated. Rather use command.Parameters.AddWithValue .
For this, you would call it many times for each parameter.
// Mention size of the nvarchar column , here i give 500 , you can use its length for #Firstname as you mention in database according to your database
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar,500).Value = TextBox1.Text;

Procedure expects a parameter which was not supplied

Towards the end of my code I am calling a stored procedure which updates a table based on the parameters passed by my page. I get the following error:
Procedure or function 'Res_invpush_UpdateInv' expects parameter '#InventoryPushSubscriptionId', which was not supplied.
Even thought my parameter value is being successfully passed - I know this because I have tested using breakpoints and when I mouse over on the parameter mentioned it gives the value of 1 so I don't know why the message is still coming.
Can somebody please show me where exactly am I going wrong or how to fix it?
SendInvUpdate.InvServices.UpdateRatePackagesRequest ur = new SendInvUpdate.InvServices.UpdateRatePackagesRequest();
SendInvUpdate.InvServices.UpdateRatePackagesOperationResponse or = new SendInvUpdate.InvServices.UpdateRatePackagesOperationResponse();
protected void Page_Load(object sender, EventArgs e)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["bb"].ConnectionString;
SqlConnection Con = new SqlConnection(connStr);
Con.Open();
SqlCommand cmd = new SqlCommand("invpush_PollForAvailableChanges", Con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter NewSysChangeVersionParam = new SqlParameter("#NewSysChangeVersion", SqlDbType.Int);
NewSysChangeVersionParam.Value = (object)NewSysChangeVersionParam ?? DBNull.Value;
NewSysChangeVersionParam.Direction = ParameterDirection.InputOutput;
NewSysChangeVersionParam.SqlDbType = SqlDbType.BigInt;
SqlDataReader sdr = cmd.ExecuteReader();
InventoryPushSubscriptionRecord rec = new InventoryPushSubscriptionRecord();
while (sdr.Read())
{
rec.InventoryPushSubId = sdr.GetInt32(0);
rec.CMName = sdr.GetString(1);
rec.NotifUrl = sdr.GetString(2);
rec.Options = sdr.GetString(3);
rec.LastSysChangeVersion = sdr.IsDBNull(4)?(long?)null:sdr.GetInt32(4);
}
if(!sdr.NextResult()) throw new System.Exception("Expected Result set 1 for InventoryChangeRecord");
InventoryChangeRecord inrec = new InventoryChangeRecord();
while (sdr.Read())
{
inrec.InventoryPushSubId= sdr.GetInt32(0);
inrec.SysChangeVersion=sdr.IsDBNull(1)?(long?)null:sdr.GetInt32(1);
inrec.InvDate=sdr.GetDateTime(2);
inrec.ResId=sdr.GetInt32(3);
inrec.RoomType=sdr.GetString(4);
inrec.InvCount=sdr.GetInt32(5);
inrec.ResName=sdr.GetString(6);
}
sdr.Close();
sdr.Dispose();
if (NewSysChangeVersionParam != null)
{
SendInvUpdate.InvServices.InventoryServiceClient isc = new SendInvUpdate.InvServices.InventoryServiceClient();
or = isc.UpdateRatePackages(request);
res = or.Results.ToString();
int Subid;
SubId=inrec.InventoryPushSubscriptionId;
SqlCommand ucmd = new SqlCommand("Res_invpush_UpdateInv", Con);
ucmd.CommandType = CommandType.StoredProcedure;
SqlParameter LastChange = new SqlParameter("#NewLastSysChangeVersion", SqlDbType.Int);
LastChange.Value = NewSysChangeVersionParam;
SqlParameter SubscriptionId = new SqlParameter("InventoryPushSubscriptionId", SqlDbType.Int);
SubscriptionId.Value = SubId;
ucmd.ExecuteNonQuery();
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
First, as Mike mentions, you should be consistent with the parameter naming.
e.g.
SqlParameter SubscriptionId = new SqlParameter("InventoryPushSubscriptionId", SqlDbType.Int);
should be
SqlParameter SubscriptionId = new SqlParameter("#InventoryPushSubscriptionId", SqlDbType.Int);
And then as #NSGaga points out, you are not really passing the parameters to the command, you just create the objects and aren't using them anywhere.
Like this:
SqlParameter LastChange = new SqlParameter("#NewLastSysChangeVersion", SqlDbType.Int);
LastChange.Value = NewSysChangeVersionParam;
ucmd.Parameters.Add(LastChange);
SubscriptionId = new SqlParameter("#InventoryPushSubscriptionId", SqlDbType.Int);
SubscriptionId.Value = SubId;
ucmd.Parameters.Add(SubscriptionId);
Hope this helps
You are not setting the parameters property for command object, your code is,
SqlCommand ucmd = new SqlCommand("Res_invpush_UpdateInv", Con);
ucmd.CommandType = CommandType.StoredProcedure;
SqlParameter LastChange = new SqlParameter("#NewLastSysChangeVersion", SqlDbType.Int);
LastChange.Value = NewSysChangeVersionParam;
SqlParameter SubscriptionId = new SqlParameter("InventoryPushSubscriptionId", SqlDbType.Int);
You can see that parameter are not assigned to command object's parameter property and hence stored procedure is not getting parameters. Just add the following before ExecuteNonQuery statement,
command.Parameters.Add(LastChange);
command.Parameters.Add(SubscriptionId );

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