我有一个简单的SQL Server存储过程:
ALTER PROCEDURE GetRowCount
(
@count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET @count=@@ROWCOUNT;
RETURN
我正在尝试访问以下C#代码中的输出参数:
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);
但是在运行代码时,代码的倒数第二行抛出了一个 NullReferenceException 异常。我错在哪里?先谢谢了!
附言:我对 SQL Procedures 还很新,所以我参考了 this article。