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

3
  • If its really necessary (i.e you cannot use a select/return value, OUT param) use a SqlInfoMessageEventHandler Commented Mar 26, 2017 at 15:48
  • I've tried not working d. How did Microsoft SQL Server Management Studio do it? Commented Mar 26, 2017 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. tf3604.com/2016/03/01/capturing-output-from-sql-server-using-c Commented Mar 26, 2017 at 15:52

1 Answer 1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.