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 );
Related
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;
I have a stored procedure that accepts an input and returns multiple columns. The stored procedure works when I execute it from SSMS and also inside of VS 2013. However when I try and execute it using SqlCommand.ExecuteReader the reader doesn't have any rows in it. If I remove the output parameters from the proc and from the SqlCommand, while still keeping the one input parameter, I am able to return the row that I am looking for.
Here is the stored proc
create Proc sp_ReturnSingleGame
#GameName varchar(100) output,
#PlatformName varchar(50) output,
#ConditionShortDescription varchar(30) output,
#RetailCost decimal(6,2) output,
#InStock bit output,
#GameID int
AS
select #GameName = GameName, #PlatformName = PlatformName,
#ConditionShortDescription = ConditionShortDescription, #RetailCost = RetailCost
from Games inner join Condition
on Games.ConditionID = Condition.ConditionID
inner join ConsolePlatform
on Games.PlatformID = ConsolePlatform.PlatformID
Where Games.GameID = #GameID
if exists (select GameID
From SaleItemized
Where GameID = #GameID)
Begin
set #InStock = 1;
end
else
Begin
set #InStock = 0;
end
Here is my C# code
public Game ReturnSingleGame(int gameId)
{
SqlConnection connection = new SqlConnection(#"server=mylaptop; integrated security=true; database=GameStoreDB;");
SqlCommand command = this.ReturnCommandForSp_ReturnSingleGame(connection, gameId);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows == true)
{
reader.Read();
game.GameId = gameId;
game.GameName = reader["GameName"].ToString();
game.PlatformName = reader["PlatformName"].ToString();
game.RetailCost = (decimal) reader["RetailCost"];
}
else
{
var exception = new ApplicationException("Game was not found");
throw exception;
}
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
return game;
}
private SqlCommand CommandForSp_ReturnSingleGame(SqlConnection connection, int gameId)
{
string storedProc = #"dbo.sp_ReturnSingleGame";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#GameName", SqlDbType.VarChar, 100, "GameName");
command.Parameters["#GameName"].Direction = ParameterDirection.Output;
command.Parameters.Add("#PlatformName", SqlDbType.VarChar, 50, "PlatformName");
command.Parameters["#PlatformName"].Direction = ParameterDirection.Output;
command.Parameters.Add("#ConditionShortDescription", SqlDbType.VarChar, 30, "ConditionShortDescription");
command.Parameters["#ConditionShortDescription"].Direction = ParameterDirection.Output;
command.Parameters.Add("#RetailCost", SqlDbType.Decimal);
command.Parameters["#RetailCost"].SourceColumn = "RetailCost";
command.Parameters["#RetailCost"].Precision = 6;
command.Parameters["#RetailCost"].Scale = 2;
command.Parameters["#RetailCost"].Direction = ParameterDirection.Output;
command.Parameters.Add("#InStock", SqlDbType.Bit);
command.Parameters["#InStock"].SourceColumn = "InStock";
command.Parameters["#InStock"].Direction = ParameterDirection.Output;
command.Parameters.Add("#GameID", SqlDbType.Int).Value = gameId;
command.Parameters["#GameID"].SourceColumn = "GameID";
command.Parameters["#GameID"].Direction = ParameterDirection.Input;
command.Prepare();
return command;
}
Stored procedure provided by you actually doesn't return any rows of data.
All it does - is just set output parameters.
So you don't need any SqlDataReader to retrieve there parameters.
Just call command.ExecuteNonQuery() and then get your parameters values from command.Parameters["#GameName"].Value and so on.
Agree with Andy.
For you snippet from one of my project is:`
DbCommand Cmd = null;
using (DataClient client = new DataClient())
{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = new SqlParameter("#ID", SqlDbType.VarChar);
parameters[0].Size = 10;
parameters[0].Direction = ParameterDirection.Output;
parameters[1] = new SqlParameter("#YourParameterName", SqlDbType.VarChar);
parameters[1].Value = Class.PropertyName;
parameters[2] = new SqlParameter("#Year", SqlDbType.Int);
client.ExecuteNonQuery("ReturnCommandForSp_ReturnSingleGame", CommandType.StoredProcedure, parameters, ref Cmd);
Then retrieve it like this
int yourReturnValue= Convert.ToInt32(Cmd.Parameters["#ID"].Value);
}
Hope it helps.
I am trying to create a SqlParameterCollection, but gives error while adding some SqlParameter in sp.Add() method.
Please help me how to add parameter and how to pass it to my another function where I declare a SqlConnection and SqlCommand.
SqlParameterCollection sp = null;
sp.Add(new SqlParameter("#CmpyCode", SqlDbType.NVarChar)).Value = CV.Global.CMPYCODE;
sp.Add(new SqlParameter("#Code", SqlDbType.NVarChar)).Value = codeName;
sp.Add(new SqlParameter("#DisplayCode", SqlDbType.NVarChar)).Value = codeName + "-";
sp.Add(new SqlParameter("#TotalDigit", SqlDbType.Int)).Value = CV.Global.PARAMTOTALDIGIT;
insertData("<Sp Name>", sp);
My another function is insertData(...)
internal static int insertData(string spName, SqlParameterCollection sp)
{
int retObj = 0;
using (SqlConnection con = new SqlConnection(CV.Global.CONSTRING))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand(spName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (sp.Count > 0)
{
foreach (SqlParameter param in sp)
cmd.Parameters.Add(param);
}
retObj = cmd.ExecuteNonQuery();
}
catch (Exception ev)
{
Util.Log(ev);
throw;
}
finally
{
try
{
con.Close();
}
catch (Exception ev) { Util.Log(ev); throw; }
}
}
return retObj;
}
I am trying to create a SqlParameterCollection and passed it to the insertData function. But it throws an error while I am calling sp.Add() method in my first function.
The error is
Object reference not set to an instance of an object
You cannot use any variable like SqlParameterCollection (a reference object) without a call to its constructor (new), but the SqlParameterCollection is an object that cannot be initialized directly with a new. It has no public constructor and can be retrieved only from the property of an existant SqlCommand.
SqlCommand cmd = new SqlCommand(commandText, connection);
SqlParameterCollection sp = cmd.Parameters;
I suggest to change your InsertData method to accept a List<SqlParameter> and let it handle the adding of the parameters to the SqlCommand that executes the command text
List<SqlParameter> sp = new List<SqlParameter>()
{
new SqlParameter() {ParameterName = "#CmpyCode", SqlDbType = SqlDbType.NVarChar, Value= CV.Global.CMPYCODE},
new SqlParameter() {ParameterName = "#Code", SqlDbType = SqlDbType.NVarChar, Value = codeName},
new SqlParameter() {ParameterName = "#DisplayCode", SqlDbType = SqlDbType.NVarChar, Value = codeName + "-"},
new SqlParameter() {ParameterName = "#TotalDigit", SqlDbType = SqlDbType.Int, Value = CV.Global.PARAMTOTALDIGIT}
};
insertData(CV.Sps.SP_INSERT_PARAM_TABLE, sp);
and insertData simply receives an optional list of SqlParameter and add them to the internal SqlCommand parameter collection if needed
internal static int insertData(string spName, List<SqlParameter> sp = null)
{
....
if(sp != null)
cmd.Parameters.AddRange(sp.ToArray());
....
}
Here is a simplified answer. I use this type of thing for a dynamic SQL query with dynamic parameters. Sometimes you don't need all parameters if you are writing a dynamic sqlquery when determining if a variable has a value.
List<SqlParameter> paramList = new List<SqlParameter>();
paramList.Add(new SqlParameter("#StartDate", StartDate));
paramList.Add(new SqlParameter("#EndDate", EndDate));
if (TicketID != "" && TicketID != null && TicketID != "undefined")
{
paramList.Add(new SqlParameter("#TicketID", TicketID));
SQLQuery = SQLQuery + " AND A.TicketID = #TicketID";
}
var Parameters = paramList.ToArray();
List<Report> ReportList = db.Database.SqlQuery<Report>(SQLQuery, Parameters).ToList();
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();**
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;