这是我们的做法:
将过程步骤包装在 aTRY
和TRANSACTION
中。然后在一个单独的处决TRY
DECLARE @lRollback bit=0
DECLARE @ErrTable TABLE (ErrNumber int,ErrSeverity int,ErrProc varchar(MAX),ErrLine int,ErrMsg varchar(MAX)) --table variable to collect errors.
BEGIN TRY -- outside begin try
BEGIN TRANSACTION -- wrap transaction
....
BEGIN TRY
...
END TRY
BEGIN CATCH
{ERROR CATCH - see below}
END CATCH
END TRY
BEGIN CATCH
SET @lRollback=1
{ERROR CATCH - see below}
ROLLBACK
BEGIN TRY
INSERT INTO errorTable (importId,errNumber,errSeverity,errProc,errLine,errMsg) --This is the db default error collection table
SELECT DISTINCT @importId,ErrNumber,ErrSeverity,ErrProc,ErrLine,ErrMsg FROM @ErrTable
END TRY
RETURN -1
END CATCH
任何时候你想在过程中发现一个错误,使用这个ERROR CATCH
:
INSERT INTO @ErrTable (ErrNumber,ErrSeverity,ErrProc,ErrLine,ErrMsg)
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;