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!