处理存储过程输出

时间:2013-05-20 07:59:13

标签: sql sql-server tsql stored-procedures

我有这个程序:

ALTER PROCEDURE [xyz].[stored_proc]
    @input1 as int, 
    @input2 as nvarchar(255)
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE ...
    SET input1=@input1
    WHERE input2=@input2 AND
    input3 NOT IN (123)
END

我想捕获update子句输出并将其作为过程输出参数返回,因此我可以在我的.net代码中处理它。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

我还没有看到任何OUTPUT子句 - 但是如果你确实拥有它,那么你需要做的就是运行这个存储过程,就像它返回一个结果集一样(来自{{1}声明):

SELECT

这假设你的存储过程中的UPDATE语句看起来像这样:

using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand cmd = new SqlCommand("[xyz].[stored_proc]", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;

    conn.Open();

    // execute your UPDATE statement with an OUTPUT clause into a SqlDataReader
    using(SqlDataReader reader = cmd.ExecuteReader())
    {
        // read the values returned from the OUTPUT clause
        while(reader.Read())
        {
            int insertedID = reader.GetInt32(0);
            // do something with those values....                
        }
    }

    conn.Close();
}