By Peter


2009-12-10 11:51:40 8 Comments

Is it possible to capture print output from a T-SQL stored procedure in .NET?

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?

-- 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 = ???

2 comments

@BraveNewMath 2013-05-13 23:05:04

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

@AdaTheDev 2009-12-10 11:58:55

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)
{
    myStringBuilderDefinedAsClassVariable.AppendLine(e.Message);
}

@Nicholas 2014-01-25 09:40:06

If you also want the rows affected count then you need a handler for the StatementCompleted event on the SqlCommand.

@Mr. TA 2015-01-20 21:06:53

@Nicholas can you elaborate? I can't get that event to work properly. Please see stackoverflow.com/questions/27993049/…

@FrenkyB 2015-03-18 08:49:42

Are you catching all messages produced within sql server with that event ? Is it possible that this event will also catch some other messages, not produced by that stored procedure ?

@IronRod 2016-08-03 17:41:33

This may be obvious but if there is no output from the proc (no print, raiseerror, etc.) then the event is not triggered. This stumped me for a while until I realized what was happening.

@IronRod 2016-08-03 17:42:29

@FrenkyB I can confirm that it will capture all output (print, raiserror, etc.) from the invoked proc or any procs or functions which it calls.

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] Search text in stored procedure in SQL Server

26 Answered Questions

16 Answered Questions

[SOLVED] Difference between decimal, float and double in .NET?

18 Answered Questions

[SOLVED] Function vs. Stored Procedure in SQL Server

21 Answered Questions

[SOLVED] .NET String.Format() to add commas in thousands place for a number

  • 2008-09-19 21:26:21
  • Seibar
  • 627736 View
  • 747 Score
  • 21 Answer
  • Tags:   c# .net

7 Answered Questions

[SOLVED] C# SQL Server - Passing a list to a stored procedure

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

21 Answered Questions

[SOLVED] Sending email in .NET through Gmail

4 Answered Questions

[SOLVED] Using stored procedure output parameters in C#

2 Answered Questions

Sponsored Content