ASP.NET SQL Server存储过程返回Message

use*_*331 5 c# sql-server asp.net stored-procedures

我有一个不需要任何参数的存储过程,并返回值0和消息:

(94 row(s) affected)

(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

我的问题是如何获取消息:

(94 row(s) affected)

(1 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

这是我调用存储过程的.NET方法:

public List<MessageClass> ChequesToUpdate()
{
    message = new List<MessageClass>();

    MessageClass item = new MessageClass();

    try
    {
        using (connection = new SqlConnection(connectionString))
        {
            connection.Open();

            using (SqlCommand command = new SqlCommand("MyStoredProcedure", connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                command.ExecuteNonQuery();

                item.message = "message";
            }
        }
    }
    catch (Exception e)
    {
        item.message = e.Message;
    }
    finally
    {
        connection.Close();
    }

    message.Add(item);

    return message;
}
Run Code Online (Sandbox Code Playgroud)

我希望将信息传入item.message,我将如何实现这一目标?

Nic*_*ico 3

在您的存储过程中,您可以查询@@ROWCOUNT,这将为您提供受影响的记录。SET现在您可以使用or语句将其存储到变量中,SELECT例如

SET MyRecordCount = @@RowCount
Run Code Online (Sandbox Code Playgroud)

或者

SELECT MyRecordCount = @@RowCount
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要跟踪单个过程中的多个操作,则可以创建多个变量并多次调用 或 或使用SET变量,例如。SELECTTABLE

DECLARE @recordCount table (Records int not null)

--RUN PROCEDURE CODE

INSERT INTO @recordCount VALUES (@@ROWCOUNT)

--RUN MORE PROCEDURECT CODE

INSERT INTO @recordCount VALUES (@@ROWCOUNT)

--RETURN THE Row Count
SELECT Records FROM @recordCount
Run Code Online (Sandbox Code Playgroud)

这会将 的值插入@@ROWCOUNT到表变量中@recordCount

接下来要获取此信息,您需要调用@recordCount表中的最后一行 select。

ExecuteNonQuery()最后,在您的代码中,您应该使用数据读取器,而不是使用该方法。

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand("MyStoredProcedure", connection))
    {
        command.CommandType = CommandType.StoredProcedure;

        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                item.message = reader.GetString(0);
            }
            reader.Close();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,该消息实际上是受影响的行的整数,而不是该术语,(98) row affected但如果您确实想要该确切的消息,则可以按照您的意愿格式化字符串。

item.message = string.Format("({0}) rows affected", reader.GetInt32(0))
Run Code Online (Sandbox Code Playgroud)