存储过程:
ALTER PROCEDURE VendorsRowcount
@RowCount int OUTPUT
AS
SET NOCOUNT ON
SELECT *
FROM dbo.Vendors
SET @RowCount = @@ROWCOUNT
RETURN @RowCount
C#:
using (var conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Pricer;Persist Security Info=True;User ID=xxx;Password=xxx"))
using (var command = new SqlCommand("VendorsRowcount", conn)
{
CommandType = CommandType.StoredProcedure
})
{
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
我收到错误:
Additional information: Procedure or function 'VendorsRowcount' expects parameter '@RowCount', which was not supplied.
在开始学习 VB 并意识到互联网上有更多 C# 资源之后,我才开始学习 C#。
这可能是个愚蠢的问题,但我已经搜索过,也许我使用的术语不正确,因为我找不到答案。
据我所知,我不需要发送参数,因为 @RowCount
已输出。
为什么会出现此错误?
最佳答案
如果您在存储过程中声明一个参数,它与声明为 OUTPUT 的事实无关。您需要从 C# 代码中传递它。另一种方法是将参数声明为可选,如另一个答案所示。但是你现在有一个问题。您如何在 C# 代码中读回该参数的值?
第一种方案,在存储过程中传递参数,并读回
conn.Open();
SqlParameter prm = command.Parameters.Add(new SqlParameter("@RowCount", SqlDbType.Int));
prm.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
Console.WriteLine(prm.Value.ToString());
conn.Close();
第二个选项,将参数设置为可选,调用SqlCommandBuilder.DeriveParameters方法来填充 C# 端的参数集合并读取它。 (有关此解决方案的效率,请阅读提供的链接中的备注部分)
-- in the stored procedure
@RowCount int = 0 OUTPUT
conn.Open();
SqlCommandBuilder.DeriveParameters(command);
command.ExecuteNonQuery();
Console.WriteLine(command.Parameters["@RowCount"].Value.ToString());
conn.Close();
然而,令我感到困惑的是,您运行了一个可能代价高昂的 SELECT *
命令,但您似乎对返回的记录不感兴趣。
在这种情况下,StoredProcedure 似乎过多并增加了维护问题,而您只需编写即可获得行数:
conn.Open();
command.CommandText = "SELECT COUNT(*) FROM Vendors";
int rowCount = Convert.ToInt32(command.ExecuteScalar());
Console.WriteLine(rowCount.ToString());
conn.Close();
关于c# - Visual C# 存储过程要求不需要的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576046/