Capturing stored procedure PRINT output in .NET
How do I access PRINT output generated by a T-SQL stored procedure in .NET? For example, consider the following stored procedure that uses PRINT to display the word "word":
<code class="language-sql">CREATE PROC usp_PrintWord AS PRINT 'word'</code>
How can I capture the output of this process using C# code?
The solution involves subscribing to the InfoMessage event on the database connection. This event is raised whenever the connected instance of SQL Server sends an information message, including a PRINT statement.
<code class="language-csharp">SqlCommand cmd = new SqlCommand("usp_printWord", TheConnection); cmd.CommandType = CommandType.StoredProcedure; myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage); void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e) { string ProcPrint = e.Message; }</code>
When the stored procedure is executed, the InfoMessage event will be triggered and the message handler will be called. The message text can be accessed through the Message property of the SqlInfoMessageEventArgs object.
The above is the detailed content of How Can I Capture T-SQL Stored Procedure PRINT Output in .NET?. For more information, please follow other related articles on the PHP Chinese website!