Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to get the SQL Server "PRINT" value in C#

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

Changing the PRINT to SELECT is not an option right now. I tried to SqlCommand.ExecuteScalar() but that didn't work.

Does anybody know if it is possible to get the value of PRINT command in SP redirected to C#?

EXAMPLE:

CREATE PROCEDURE doXYZ
AS
BEGIN
   PRINT 'XYZ'
END

Now in C# I need to get the value 'XYZ'.... any ideas?

like image 897
Amin J Avatar asked Apr 21 '11 21:04

Amin J


People also ask

How do I print the value of a variable in SQL?

You can use PRINT or simply SELECT. You can do it in the following way with SQL Server Query Analyzer... You can also use a @tablevariable in addition to the suggestion by Alan. You use regular INSERT to populate it and SELECT to retrieve the data.

Does SQL have a print statement?

It helps to track the query progress. Usually, we use the SQL PRINT statement to print corresponding messages or track the variable values while query progress. We also use interactions or multiple loops in a query with a while or for a loop. We can also use the SQL PRINT statement to track the iteration.

Which of the following subscription is required to display data from SQL print statement?

You need to subscribe to the SqlConnection. InfoMessage Event.


2 Answers

You can use the SqlConnection.InfoMessage event.

like image 138
Mark Cidade Avatar answered Oct 15 '22 06:10

Mark Cidade


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;              
        }
    }
}
like image 39
Tim Partridge Avatar answered Oct 15 '22 06:10

Tim Partridge