我有一个简单的SQL Server存储过程:访问SQL Server存储过程的输出参数
ALTER PROCEDURE GetRowCount
(
@count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET @[email protected]@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。我哪里错了?提前致谢!
P.S.我是SQL程序新手,所以我提到了this article。
ANKIT我更新了我的代码,你必须只改变你的指令的ExecuteNonQuery –