为什么SqlCommand.ExecuteNonQuery抛出的SqlException包含所有PRINT为错误?

时间:2010-02-01 16:19:23

标签: sql tsql sqlcommand sqlexception

当我运行以下代码段

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);
}

我收到以下消息:

SQL_Error
A
B
C

ex.Errors有4个条目(与打印对应的3 SqlError的{​​{1}}为0(真实错误为18)

但是,如果我将SqlError.Class替换为ExecuteNonQuery,我会得到预期的结果:

邮件为ExecuteScalar,我在SQL_Error ...

中只有一个条目

有没有办法避免ex.Errors ??

的奇怪行为

2 个答案:

答案 0 :(得分:1)

不,你无法避免这种行为。它是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 :(得分:0)

ExecuteNonQuery通常返回记录集,而ExecuteScalar返回第一行+第一列。