2012-04-10 61 views
0

我有ADO.Net代码如下,调用存储过程。在存储过程中,我首先通过SELECT查询获取结果集,然后在SELECT语句之后调用RAISERROR(如果传递的@companyId参数值不存在)。我已经多次使用@companyId的值对此代码运行单元测试,因此RAISEERROR被调用,但我从来没有看到ExecuteReader的调用会抛出错误。 为什么这种奇怪的违反直觉的事情发生的原因是什么?非常棘手的ADO.Net的情况,不会抛出一个错误,但应该

sqlCmd = new SqlCommand("dbo.xyz_sp_Attributes_GetValues", new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["VHA_EDM_ConnectionString"].ConnectionString)); 
sqlCmd.CommandType = CommandType.StoredProcedure; 
sqlCmd.Parameters.AddWithValue("@attributeId", attributeId); 
sqlCmd.Parameters.AddWithValue("@companyId", companyId); 
sqlCmd.Parameters.AddWithValue("@attributeScope", "Company"); 
sqlCmd.Connection.Open(); 
SqlDataReader dr = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection); 
while (dr.Read()) 
{ 
    attributeValue = dr["AttributeValue"].ToString(); 
} 

存储过程的代码是一样的东西下面

SELECT col1, col2, ... where CompanyId = @companyId and AttributeId = @attributeId 
if @companyId not exists (select companyId from Company where CompanyId = @companyId) 
begin 
set @errMessage = N'Invalid Company Error' 
RAISERROR (@errMessage, 16, 1) 
end 

回答

1

在这种情况下,有将返回一个以上的记录。第一个是空的,这就是为什么你没有得到任何错误。你必须调用NextRecordset来获取错误。

dr.NextResult(); // This will throw the error caused by RAISEERROR 

这将是很容易做的错误在客户端代码,而不是调用RAISEERROR这在任何情况下都会有作为例外处理检查。

Catch a Sql Server RAISERROR at client side using SqlDataReader

+0

我只返回一个结果集。你为什么说我返回多个结果集? – Sunil 2012-04-10 22:16:21

+0

你没有这样做,但SPs结果的方式是由ADO.NET返回的,它变成两个记录集。你从来没有遇到过这种情况,然后使用[SET NOCOUNT ON](http://stackoverflow.com/questions/1483732/set-nocount-on-usage) – 2012-04-10 22:31:52

+0

好的。我现在得到你。感谢您非常有帮助的回复。 – Sunil 2012-04-11 22:19:00

相关问题