在.NET中捕获存储过程打印输出

时间:2009-12-10 11:51:40

标签: c# .net stored-procedures

是否可以从.NET中的T-SQL存储过程捕获打印输出?

我有很多遗留过程使用print作为errorMessaging的方法。例如,是否可以从以下PROC访问套印“字”?

-- The PROC
CREATE PROC usp_PrintWord AS
    PRINT 'word'
// Some C# Code to would like to pull out 'word'
SqlCommand cmd = new SqlCommand("usp_printWord", TheConnection);
cmd.CommandType = CommandType.StoredProcedure;
// string ProcPrint = ???

3 个答案:

答案 0 :(得分:135)

您可以通过向连接上的InfoMessage事件添加事件处理程序来完成此操作。

myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);

void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
    myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}

答案 1 :(得分:8)

如果您想在LinqPad的输出控制台中捕获打印输出,这非常方便:

SqlConnection conn = new SqlConnection(ConnectionString);
//anonymous function to dump print statements to output console
conn.InfoMessage += (object obj, SqlInfoMessageEventArgs e)=>{
                e.Message.Dump();
            };

答案 2 :(得分:0)

要将输出转换为变量:

string printOutput = "";

using (var conn = new SqlConnection(...))
{
    // handle this event to receive the print output
    conn.InfoMessage += (object obj, SqlInfoMessageEventArgs e) => {
        printOutput += e.Message;
    };

    // execute command, etc.
}

Console.Write(printOutput);