When I run the following snippet
try
{
using (SqlConnection conn = new SqlConnection("I m shy"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "PRINT A ;PRINT B ;PRINT C ;RAISERROR( SQL_Error , 18, 1)";
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
I get the following message:
SQL_Error
A
B
C
and ex.Errors
has 4 entries (The 3 SqlError
s corresponding to the prints have a SqlError.Class
of 0 (vs. 18 for the real error)
However, if I replace ExecuteNonQuery
with ExecuteScalar
, I get the expected result:
The message is SQL_Error
and I only have one entry in ex.Errors
...
Is there any way to avoid the strange behavior of cmd.ExecuteNonQuery
??