在.net中我们经常用到try catch.不过在sqlserver中我们也可以使用try catch捕捉错误,在这里把语法记录下来和大家分享一下,


--构建存储过程
CREATE PROCEDURE TestProc
@Para  INT
AS 

BEGIN TRAN
DECLARE @tran_error int
SET @tran_error = 0 

BEGIN TRY 

           ---这里是存储过程的业务逻辑

            DELETE FROM table
END TRY

BEGIN CATCH   --捕捉错误
        SET @tran_error = @tran_error + 1
END CATCH


IF(@tran_error > 0)
BEGIN
      SELECT -1
      ROLLBACK TRAN
END
ELSE
BEGIN
      SELECT 1
      COMMIT TRAN
END
GO