Need to get the SQL Server “PRINT” value in C#

前端 未结 2 1461
太阳男子
太阳男子 2020-12-31 04:31

I have a SP that Prints the results into SQL Server, but I need to use that value in C#.

Changing the PRINT<

相关标签:
2条回答
  • 2020-12-31 05:07

    You can use the SqlConnection.InfoMessage event like so:

    using System.Data;
    using System.Data.SqlClient;
    
    namespace foo
    {
        class bar
        {
            static public void ExecuteStoredProc()
            {
                var connectionString = "Data Source=.;Integrated Security=True;Pooling=False;Initial Catalog=YourDatabaseName";
                using (var connection = new SqlConnection(connectionString))
                using (var command = new SqlCommand("dbo.YourStoredProcedure", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@YourParameterName", "YourParameterValue");
    
                    connection.Open();
                    // wire up an event handler to the connection.InfoMessage event
                    connection.InfoMessage += connection_InfoMessage;
                    var result = command.ExecuteNonQuery();             
                    connection.Close();
                }
            }
    
            static void connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
            {
                // this gets the print statements (maybe the error statements?)
                var outputFromStoredProcedure = e.Message;              
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 05:16

    You can use the SqlConnection.InfoMessage event.

    0 讨论(0)
提交回复
热议问题