2012-07-11 18 views
0

在SQL Server中,您需要檢查每個SQL語句的錯誤。例如,如果我有一個交易3次更新,我需要一些這樣的代碼:如何爲SQL Server中的T-SQL中的事務捕獲錯誤?

declare @HasError int 
begin tran 
Update tab1 set .... 
Set @HasError = @@error; 
Update tab2 set ... 
Set @HasError = @@error; 
Update tab3 set ... 
Set @HasError = @@error; 

If @HasError<>0 
    rollback tran; 
else 
commit tran; 

這種情況更簡單的代碼,任何其他解決辦法?例如,類似於C#風格:

begin tran 
    try 
    { 
     Update tab1 set ....  
     Update tab2 set ... 
     Update tab3 set ... 
     commit tran; 
    }catch(error){ 
     rollback tran; 
    } 
+0

是的,這是可能的。 看看[這個msdn文章](http://msdn.microsoft.com/en-us/library/ms179296(v = sql.105).aspx)。 – 2012-07-11 13:31:18

+0

@KentZhou - 您還應該提供最能滿足您需求的答案。 – 2012-07-16 15:59:32

回答

3

您可以使用一個嘗試捕捉語法在C#

BEGIN TRY 
    -- .... 
END TRY 
BEGIN CATCH 
    -- .... 
END CATCH 
+2

不要只是回滾,將錯誤返回給用戶,甚至更好地將其記錄在錯誤表中。如果您將有關錯誤的信息放入表變量中,則該信息不會回滾,您可以插入到表中。存儲錯誤信息對於判斷出錯是非常寶貴的。 – HLGEM 2012-07-11 14:17:32

相關問題