113

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 = ???
GSerg
  • 76,472
  • 17
  • 159
  • 346
Peter
  • 47,963
  • 46
  • 132
  • 181
  • 5
    It maybe not only about errors. I will try to use this to keep track of progress of a long running stored proc by watching the informative output. – Csaba Toth Apr 18 '13 at 17:14

3 Answers3

159

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)
    {
       Console.WriteLine(e.Message);
    }
BraveNewMath
  • 8,090
  • 5
  • 46
  • 51
AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
  • 6
    If you also want the rows affected count then you need a handler for the StatementCompleted event on the SqlCommand. – Nicholas Jan 25 '14 at 09:40
  • @Nicholas can you elaborate? I can't get that event to work properly. Please see http://stackoverflow.com/questions/27993049/retrieve-record-counts-from-multiple-statements – Mr. TA Jan 20 '15 at 21:06
  • 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 ? – FrenkyB Mar 18 '15 at 08:49
  • 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. – AdvApp Aug 03 '16 at 17:41
  • @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. – AdvApp Aug 03 '16 at 17:42
11

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();
            };
BraveNewMath
  • 8,090
  • 5
  • 46
  • 51
6

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. here
    // 
}

Console.Write(printOutput);
Keith
  • 20,636
  • 11
  • 84
  • 125