ank*_*311 3 c# t-sql sql-server stored-procedures
我有一个简单的SQL Server存储过程:
ALTER PROCEDURE GetRowCount
(
@count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET @count=@count+@@ROWCOUNT;
RETURN
Run Code Online (Sandbox Code Playgroud)
我正在尝试初始化并访问以下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.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);
Run Code Online (Sandbox Code Playgroud)
但是在运行代码时,会在代码InvalidCastException
的倒数第二行抛出一个(我调试并检查了Value属性中没有返回任何内容).
如何在代码中正确初始化输出参数?提前致谢!