简体   繁体   中英

Returning results and messages from a SQL Stored procedure in a C# winform

I have been supplied with a Stored Procedure that needs to be run in SSMS with 'results to text' selected so that the Results and Messages are displayed in the correct order.

The reason is that the stored proc is used to build a script for transferring customer setup from one database to another, Print statements are used to wrap informational messages and error handling around insert statements...

PRINT 'Inserting values into [AIP_M_SITE_LABELS]'

INSERT INTO [AIP_M_DEV_SITE_LABELS] VALUES(2,90014,'Stage Indicators - Total Stages Of',0,'of',0,0)

INSERT INTO [AIP_M_DEV_SITE_LABELS] VALUES(2,90025,'Ledger _ Ref',0,'N/A',0,0)

IF @@ERROR <> 0

BEGIN

Print('Error Inserting into [AIP_M_SITE_LABELS]')

GOTO ExecutionFail

END

Is there a way to execute this stored procedure in my c# winform that will allow me to save this output? I've so far managed to get the result set(s) and the messages separately but not yet 'merged' and in the correct order.

You need to subscribe to the InfoMessage event of your SQLConnection object. Something like this should work:

Define this at the class level so your event handler can access it:

StringBuilder sb = new StringBuilder("");

For wherever your SQL stuff is:

            var conn = new SqlConnection("your connection string");
        conn.Open();
        conn.InfoMessage += conn_InfoMessage;
        var commandText = "your SP name";
        var command = new SqlCommand(commandText, conn) {CommandType = CommandType.StoredProcedure};
        command.ExecuteNonQuery();

The event handler to grab the data (doesn't need to be static, but mine is):

    static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
    {
        sb.AppendLine(e.Message);
    }


Just saw your note about getting the print and job results in 1 shot. Instead of using .ExecuteNonQuery(), use .ExecuteReader() and use a SQLDataReader like normal. Your InfoMessage event should still fire, and you'll need to manually merge the results of both the SQLDataReader and InfoMessage event somewhere in your method. Be careful with appending to your class level stringbuilder and doing stuff with it in the method that is causing that event to fire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM