0

How can I retrieve a string generated by the PRINT t-sql command of SQL Server in my .net application

Example Microsoft SQl Server Management Studio :

enter image description here

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
Emre BOSTAN
  • 33
  • 1
  • 7
  • If its really necessary (i.e you cannot use a select/return value, OUT param) use a [`SqlInfoMessageEventHandler`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlinfomessageeventhandler(v=vs.110).aspx) – Alex K. Mar 26 '17 at 15:48
  • I've tried not working d. How did Microsoft SQL Server Management Studio do it? – Emre BOSTAN Mar 26 '17 at 15:50
  • That's the way to do it, if its not working then you must not be using it correctly. There are many examples out there E.g. http://www.tf3604.com/2016/03/01/capturing-output-from-sql-server-using-c/ – Alex K. Mar 26 '17 at 15:52

1 Answers1

7

In order to retrieve these message, you can use the InfoMessage event available on the SqlConnection class.

using (SqlConnection conn = new SqlConnection("..."))
{
    conn.InfoMessage += (sender, e) =>
    {
        Console.WriteLine($"{e.Source}-{e.Message}");
    };
    conn.Open();
    using (SqlCommand command = new SqlCommand("PRINT 'Hello World'", conn))
    {
        command.ExecuteNonQuery();
    }
}
Cyril Durand
  • 15,834
  • 5
  • 54
  • 62