Access to SQL Server messages via ADO.NET

后端 未结 3 1689
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 10:59

Is it possible to access the SQL Server \"by-product messages\" via ADO.NET? Due to the lack of words, by \"by-product messages\" I mean the output which appears in the Mess

3条回答
  •  Happy的楠姐
    2020-12-10 11:26

    Thank you for the response above. I just did a little experiment and found a little unexpected glitch (a bug?) when reading messages (in this case produced by SET STATISTICS TIME ON) from a multi-recordset result. As indicated below, one has to call NextResult even after the last resultset in order to get the last message. This is not needed in the case of a single recordset result.

    using System;
    using System.Data.SqlClient;
    
    namespace TimingTest
    {
        class Program
        {
    
            static void Main(string[] args)
            {
    
                SqlConnection conn = new SqlConnection("some_conn_str");
                conn.Open();
    
                conn.InfoMessage += new SqlInfoMessageEventHandler(Message);
    
                SqlCommand cmd = new SqlCommand("some_sp", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
    
                SqlDataReader rdr = cmd.ExecuteReader();
    
                while (rdr.Read()) { };
    
                rdr.NextResult();
    
                while (rdr.Read()) { };
    
                // this is needed to print the second message
                rdr.NextResult();
    
                rdr.Close();
    
                conn.Close();
    
            }
    
            static void Message(object sender, SqlInfoMessageEventArgs e)
            {
                Console.Out.WriteLine(e.Message);
            }
    
        }
    }
    

提交回复
热议问题