I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
@count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET @count=@count+@@ROWCOUNT;
RETURN
I am trying to initialize and access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.Parameters.Add(new SqlParameter("@count", SqlDbType.Int));
cmd.Parameters["@count"].Direction = ParameterDirection.Output;
con.Open();
cmd.Parameters["@count"].Value=5;
cmd.ExecuteNonQuery();
int ans = (int)(cmd.Parameters["@count"].Value);
Console.WriteLine(ans);
But on running the code, an InvalidCastException
is being thrown at the second last line of the code (I debugged and checked that nothing is being returned in the Value attribute).
How can I properly initialize the output parameter in code? Thanks in advance!
You need to change the ParameterDirection to ParameterDirection.InputOutput
Have a look here for an example: how to get return value from procedure sql server 2005 to c#
You don't have to initialize an output
parameter. Use ParameterDirection.InputOutput
to pass the value to the stored procedure.
The most likely cause for a type exception is that the procedure returns DBNull.Value
. You can test that like:
var ans = cmd.Parameters["@count"].Value as int?;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.