ExecuteNonQuery
returns the total number of affected row(s). So, if you want just total number of row(s) then simply you can get it using below statement:
var x = command.ExecuteNonQuery();
Otherwise, you have to use user define RAISERROR
message in the stored procedure and catch it from C# connection.InfoMessage
event. I've setup a test environment and tested it. I've created a table and inserted some data to check my SQL & C# code. Please check below SQL & C# code.
SQL:
Create Table psl_table
(
[values] NVarChar(MAX)
)
Insert Into psl_table Values('a')
Insert Into psl_table Values('a')
Insert Into psl_table Values('a')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Insert Into psl_table Values('b')
Create Proc MyStoredProcedure
As
Begin
-- Declare a variable for Message
Declare @Msg NVarChar(MAX)
-- 1st SQL Statement
Update psl_table Set [Values]='a' Where [Values]!='a'
-- Generate the message and print that can get from C#
Set @Msg = '(' + Convert(NVarChar,@@RowCount) + ' row(s) affected)'
RAISERROR( @Msg, 0, 1 ) WITH NOWAIT
-- 2nd SQL Statement
Update psl_table Set [Values]='a'
-- Generate the message and print that can get from C#
Set @Msg = '(' + Convert(NVarChar,@@RowCount) + ' row(s) affected)'
RAISERROR( @Msg, 0, 1 ) WITH NOWAIT
End
In this SQL, I've declared a variable @Msg to store message and built-in function RAISERROR to throw the message.
C# CODE:
public List<MessageClass> ChequesToUpdate()
{
message = new List<MessageClass>();
MessageClass item = new MessageClass();
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
connection.InfoMessage += delegate (object sender, SqlInfoMessageEventArgs e)
{
item.message = e.Message;
};
using (SqlCommand command = new SqlCommand("MyStoredProcedure", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
item.message = e.Message;
}
finally
{
connection.Close();
}
message.Add(item);
return message;
}
I've modified your code for desired output. I've used connection.InfoMessage event to catch message that throw from SQL.
For testing purpose I printed output in Console.
Output:
