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#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With