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

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

我有很多遗留的处理程序,它们使用打印作为 errorMessaging 的手段。例如,是否可以从下面的 PROC 访问输出‘ word’?

-- 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 = ???
42112 次浏览

You can do this by adding an event handler to the InfoMessage event on the connection.

 myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);


void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
Console.WriteLine(e.Message);
}

This is really handy if you want to capture Print output in LinqPad's output console:

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

To get the output into a variable:

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