2012-04-10 62 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

相關問題