C# 在 .NET 中捕获存储过程打印输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1880471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capture Stored Procedure print output in .NET
提问by Peter
Is it possible to capture print output from a T-SQL stored procedure in .NET?
是否可以从 .NET 中的 T-SQL 存储过程捕获打印输出?
I have a lot of legacy procs that use the print as means of errorMessaging. An example, is it possible to access the outprint 'word' from following PROC?
我有很多使用打印作为 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 = ???
采纳答案by AdaTheDev
You can do this by adding an event handler to the InfoMessageevent on the connection.
您可以通过向连接上的InfoMessage事件添加事件处理程序来实现此目的。
myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}
回答by BraveNewMath
This is really handy if you want to capture Print output in LinqPad's output console:
如果您想在 LinqPad 的输出控制台中捕获打印输出,这真的很方便:
SqlConnection conn = new SqlConnection(ConnectionString);
//anonymous function to dump print statements to output console
conn.InfoMessage += (object obj, SqlInfoMessageEventArgs e)=>{
e.Message.Dump();
};
回答by Keith
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);