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?
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.
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.
You need to subscribe to the SqlConnection. InfoMessage Event.
You can use the SqlConnection.InfoMessage
event.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With