Retrieving PRINT Output from Stored Procedures in .NET Applications
Effectively capturing PRINT
output from stored procedures in .NET applications is essential, particularly when dealing with older systems that use PRINT
statements for error handling and logging. Let's illustrate how to capture the output "word" from the stored procedure "usp_PrintWord":
<code class="language-sql">-- Stored Procedure CREATE PROC usp_PrintWord AS BEGIN PRINT 'word' END;</code>
.NET Solution:
The following steps demonstrate how to capture this PRINT
output within your .NET code:
InfoMessage
event of your SQL connection. This event fires for informational messages generated during database interactions.<code class="language-csharp">myConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);</code>
Message
property of the SqlInfoMessageEventArgs
to retrieve the PRINT
output.<code class="language-csharp">void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e) { Console.WriteLine(e.Message); }</code>
SqlCommand
as you normally would. The PRINT
output will be captured and displayed in the console (or wherever your event handler directs the output).This approach provides a simple and effective way to access PRINT
output from your stored procedures.
The above is the detailed content of How Can I Capture PRINT Output from Stored Procedures in .NET?. For more information, please follow other related articles on the PHP Chinese website!