I have to use stored procedures for accessing data and also consume messages (like PRINT 'hello'
) sent from the DB engine.
When I a use InfoMessage
event of SQL connection and fill the data into DataTable
, everything works perfect.
However, when I have to read data sequentially and use SqlDataReader.ExecuteReaderAsync
, connection stops firing InfoMessage after first select statement in the stored procedure:
C# code:
using (SqlConnection con = new SqlConnection("connection-string"))
{
con.Open();
con.InfoMessage += (s, e) => {
Console.WriteLine(e.Message);
};
using (SqlCommand command = new SqlCommand("spTestMessage", con))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = await command.ExecuteReaderAsync();
int cntr = 0;
while (reader.Read())
{
Console.WriteLine($"Loaded row {cntr++}");
}
// reader.NextResult(); // this line forces firing rest of InfoMessage events
}
}
SQL Stored Procedure:
CREATE PROCEDURE [dbo].[spTestMessage]
AS
PRINT 'Before select 1'
select * from MyTable
PRINT 'After select 1'
PRINT 'Before select 2'
select * from MyTable
PRINT 'After select 2'
Program output:
Before select 1
Why it stops working? I thing there is something wrong with Reader, because when I use command.ExecuteNonQueryAsync();
instead of command.ExecuteReaderAsync();
, it also works.
I incidentally found out, that commented row reader.NextResult();
forces the connection to flush the messages and fire remaining events. However, its a very unlucky workaround.
Thanks for any help!