如何在SQL Server的T-SQL中捕获事务的错误?

时间:2012-07-11 13:28:56

标签: sql sql-server-2008 tsql

在SQL Server中,您需要检查每个SQL语句的错误。例如,如果我在一个事务中有3个更新,我需要一些代码,如:

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#style:

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

2 个答案:

答案 0 :(得分:3)

您可以像在c#

中一样使用try catch语法
 BEGIN TRY
    -- ....
 END TRY
 BEGIN CATCH
    -- ....
 END CATCH

答案 1 :(得分:0)

Click here to see => Why do I really need to use SET XACT_ABORT ON

<强> Click here to see How SET NOCOUNT ON Improves SQL Server Stored Procedure Performance

Begin Try
    SET NOCOUNT ON
    Set XACT_ABORT ON
    Begin Tran
        --Your Query
    Commit Tran
End Try

Begin Catch
    RollBack Tran
    Select ERROR_MESSAGE() as Msg, ERROR_NUMBER() as Num
End Catch