Home >Backend Development >C++ >How Can I Capture T-SQL Stored Procedure PRINT Output in .NET?

How Can I Capture T-SQL Stored Procedure PRINT Output in .NET?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 16:42:10492browse

How Can I Capture T-SQL Stored Procedure PRINT Output in .NET?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn