Why does the SqlException thrown by SqlCommand.ExecuteNonQuery contain all the PRINT as errors?

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.Errorshas 4 entries (3 SqlErrorcorresponding to fingerprints, have SqlError.Class0 (versus 18 for a real error)

However, if I replaced ExecuteNonQuerywith ExecuteScalar, I get the expected result:

Message SQL_Error, and I have only one entry in ex.Errors...

Is there any way to avoid weird behavior cmd.ExecuteNonQuery??

+3
source share
2 answers

, . , TdsParser.ThrowExceptionAndWarning()

,

  bool breakConnection = this.AddSqlErrorToCollection(ref temp, ref this._errors) | this.AddSqlErrorToCollection(ref temp, ref this._attentionErrors);
        breakConnection |= this.AddSqlErrorToCollection(ref temp, ref this._warnings);
        breakConnection |= this.AddSqlErrorToCollection(ref temp, ref this._attentionWarnings);

, - _error _attentionErrors ExecuteScaler ExecuteNonQuery.

, , , , .

, , . SQLExecption.Error

+1

ExecuteNonQuery , ExecuteScalar + .

0

Source: https://habr.com/ru/post/1730886/


All Articles