如何在使用T-SQL时有效地捕获错误

时间:2013-08-07 16:47:43

标签: sql-server tsql error-handling try-catch

我正在寻找一种方法来捕获错误,而不使用经典的try catch,因为此代码不适用于我的SQL版本(2005)

BEGIN TRY
    SELECT 1/0;
END TRY
BEGIN CATCH
    EXECUTE usp_GetErrorInfo;
END CATCH;

ERROR:

Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'TRY'.
Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'END'.

任何解决方法?或者我做错了什么?

2 个答案:

答案 0 :(得分:0)

BEGIN TRY
   Try Statement 1
   Try Statement 2
   ...
   Try Statement M
END TRY
BEGIN CATCH
   Catch Statement 1
   Catch Statement 2
   ...
   Catch Statement N
END CATCH

是标准的try..catch语法。它在2005版本中得到支持。有关详细信息,请参阅here

答案 1 :(得分:0)

如果您设置的cpmapitbility级别较低且无法在不破坏的情况下进行更改,那么我们陷入错误的旧方式是

DECLARE @Error INT 
DECLARE @ErrorMessage NVARCHAR(500)


SET @Error = 0  
SET @ErrorMessage = ''
BEGIN TRAN
IF @Error = 0 
   BEGIN
      Do something
      SET @Error = @@Error         
   END

IF @Error = 0 
   BEGIN
      Do something else
      SET @Error = @@Error         
   END

 --this code must be the last code in the proc or batch
IF @Error = 0
   BEGIN    
      COMMIT TRAN
   END 
ELSE
   BEGIN    
      ROLLBACK TRAN
   END 

关键是你必须在每次采取行动后检查错误。例如,对于三个分组步骤,不要执行一次。