I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
@count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET @count=@@ROWCOUNT;
RETURN
I am trying to 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.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@count", SqlDbType.Int));
cmd.Parameters["@count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["@count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I’d suggest you put your
SqlConnectionandSqlCommandinto using blocks so that their proper disposal is guaranteed.Also, if I’m not mistaken, the output parameters are only available after you’ve completely read the resulting data set that’s being returned.
Since you don’t seem to need that at all – why not just use
.ExecuteNonQuery()instead? Does that fix the problem?Also : since it seems you’re only really interested in the row count – why not simplify your stored procedure to something like this:
and then use this snippet in your C# code: