Visual C#存储过程询问不需要的参数

时间:2014-08-29 20:49:38

标签: c# sql sql-server-2008

存储过程:

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();
}

我收到错误:

  

其他信息:程序或功能' VendorsRowcount'期望参数' @ RowCount',这是未提供的。

我在学习VB之后学习C#,并意识到C#上有更多的互联网资源。

这可能是一个愚蠢的问题,但我搜索过,也许我使用的术语不正确,因为我找不到答案。

据我所知,我不需要发送参数,因为@RowCount已输出。

为什么我会收到此错误?

3 个答案:

答案 0 :(得分:3)

如果在存储过程中声明一个参数,则它与声明为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#端的Parameter集合并将其读回。 (请阅读提供的有关此解决方案效率的链接中的备注部分)

-- 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();

答案 1 :(得分:2)

您需要传入该参数。以下是如何执行此操作的一个很好的示例:

Get output parameter value in ADO.NET

答案 2 :(得分:1)

如果参数应该是可选的,则必须在存储过程中提供默认值。

例如: @RowCount int OUTPUT = 0