/*當一段大的SQL語句中調用了多個預存程序,被調用的預存程序中又調用了多個預存程序,如此經過多次嵌套調用後,當遇到如重複主鍵、或是不滿足商務邏輯時需要復原整個事務,則可以使用下面的模式進行處理。也可以不進行raiserror進行直接計數。當SET XACT_ABORT ON後如果執行出錯會自動復原到最外層事務,但如果是商務邏輯出錯則需要進行手動計數和手動復原,即下面的DECLARE @ErrorSave INT SET @ErrorSave = 0|EXECUTE @ErrorSave = TTransProc @PriKey,@CharCol/*調用預存程序*/|SET @ErrorSave = @ErrorSave + @@ERROR|RETURN @ErrorSave*/
/*建立測試表*/
CREATE TABLE TestTrans (Cola int NOT NULL ,Colb char(3) NOT NULL,constraint PK_TestTrans primary key (Cola))
GO
/*建立預存程序*/
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/*預存程序3*/
CREATE PROCEDURE TTransProc @PriKey INT, @CharCol CHAR(3)
AS
DECLARE @ErrorSave INT SET @ErrorSave = 0
INSERT INTO TestTrans VALUES (@PriKey + 2, @CharCol)
IF(@PriKey = 0) BEGIN
RAISERROR('TTransProc User error',16,1)
SET @ErrorSave = @ErrorSave + @@ERROR
END
RETURN @ErrorSave
GO
/*預存程序2*/
CREATE PROCEDURE STransProc @PriKey INT, @CharCol CHAR(3)
AS
DECLARE @ErrorSave INT SET @ErrorSave = 0
INSERT INTO TestTrans VALUES (@PriKey + 1, @CharCol)
EXECUTE @ErrorSave = TTransProc @PriKey,@CharCol/*調用預存程序3*/
IF(@PriKey = 6) BEGIN
RAISERROR('STransProc User error',16,1)
SET @ErrorSave = @ErrorSave + @@ERROR
END
RETURN @ErrorSave
GO
/*預存程序1*/
CREATE PROCEDURE FTransProc @PriKey INT, @CharCol CHAR(3)
AS
DECLARE @ErrorSave INT SET @ErrorSave = 0
INSERT INTO TestTrans VALUES (@PriKey, @CharCol)
EXECUTE @ErrorSave = STransProc @PriKey,@CharCol/*調用預存程序2*/
IF(@PriKey = 11) BEGIN
RAISERROR('FTransProc User error',16,1)
SET @ErrorSave = @ErrorSave + @@ERROR
END
RETURN @ErrorSave
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
---------------------測試----------------------
/*設定此標記當執行過程中出錯則自動復原*/
SET XACT_ABORT ON
/*此變數用來儲存使用者自訂的錯誤,如當不滿足業務要求時,使用RAISERROR拋出錯誤,然後進行計數,以便外層事務進行復原*/
DECLARE @ErrorSave INT SET @ErrorSave = 0
BEGIN TRANSACTION OutOfProc
PRINT 'OA:@@ERROR='+ CONVERT(varchar,@@ERROR)+'|@ErrorSave='+ CONVERT(varchar,@ErrorSave)
EXECUTE @ErrorSave = FTransProc 6,'aaa'
PRINT 'OB:@@ERROR='+ CONVERT(varchar,@@ERROR)+'|@ErrorSave='+ CONVERT(varchar,@ErrorSave)
SET @ErrorSave = @ErrorSave + @@ERROR
IF (@ErrorSave = 0) BEGIN
COMMIT TRANSACTION OutOfProc
END ELSE BEGIN
ROLLBACK TRANSACTION OutOfProc
END
GO
-------------------------------------------
--SELECT * FROM testTrans
--DELETE FROM testTrans