在C#中访问SQL Server存储过程输出参数

3

我有一个简单的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

Ankit,我更新了我的代码,你只需要更改你的指令ExecuteNonQuery。 - Aghilas Yakoub
5个回答

12
我建议您将SqlConnectionSqlCommand放入using块中,以确保它们的正确处理。
此外,如果我没有错的话,在完全读取返回的数据集之后才能使用输出参数。
既然您似乎根本不需要这个 - 为什么不使用.ExecuteNonQuery()呢?那样可以解决问题吗?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add(new SqlParameter("@count", SqlDbType.Int));
    cmd.Parameters["@count"].Direction = ParameterDirection.Output;

    con.Open();
    cmd.ExecuteNonQuery();  // *** since you don't need the returned data - just call ExecuteNonQuery
    int ans = (int)cmd.Parameters["@count"].Value;
    con.Close();

    Console.WriteLine(ans);
}

另外,既然您似乎只对行数感兴趣,为什么不将存储过程简化为以下内容:

ALTER PROCEDURE GetRowCount
AS
   SELECT COUNT(*) FROM Emp WHERE age > 30;

然后在你的C#代码中使用以下代码片段:

    con.Open();

    object result = cmd.ExecuteScalar();

    if(result != null)
    {
        int ans = Convert.ToInt32(result);
    }

    con.Close();

我的错,我在代码中有那一行,但不知何故在这里漏掉了。我已经编辑了问题。 - ankit0311
@ankit0311:更新了我的回复 - 尝试使用.ExecuteNonQuery() - 这样能解决问题吗? - marc_s

1

你必须明确指定它是存储过程而不是查询

cmd.CommandType = CommandType.StoredProcedure;

我的错,我在代码中有那一行,但不知何故在这里漏掉了。我已经编辑了问题。 - ankit0311

1

只需使用ExecuteNonQuery,您无法在此情况下使用带有输出参数的ExecuteReader

cmd.ExecuteNonQuery(); 

或者,如果你想尝试使用ExecuteScalar和ReturnValue


我的错,我在代码中有那一行,但不知何故在这里漏掉了。我已经编辑了问题。 - ankit0311

0

你应该添加

cmd.CommandType = CommandType.StoredProcedure 

在调用它之前


0

我找到问题了,是连接字符串的问题。 但现在,在代码中:

 usuary = (string)cmd.Parameters["@USUARIO"].Value;
password = (string)cmd.Parameters["@CLAVE"].Value;

编译器提示数值为空...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接