|
我有一个相当复杂的嵌套SP(逻辑上),IF BEGIN ENDELSE嵌套逻辑中有多个端点,其中逻辑失败,而我RAISERROR和两个地方导致成功和和和SQL被执行。& O/ D8 Y' ]! d" m# }. U
如何在SP末尾捕获错误并执行 IF Error Count>0 THEN ROLLBACK
3 j& [3 H& J6 y3 C4 g# lDECLARE @errCount int=0DECLARE @DataSetCount int=0DECLARE @countCurrent int=0DECLARE @countHistorical int=0IF (isnumeric(@DataSetID)=(0) OR @DataSetID=(0)) BEGIN RAISERROR('The DataSet specfied does not appear to be valid',5,1)ENDELSEIF (@Destination='C' OR @Destination='H BEGIN if Exists (SELECT NULL from tblOpportunityDataSets where DataSetID=@DataSetID) BEGIN SET @countCurrent=(SELECT COUNT(1) from tblOptyRecordsCurrent where DataSetID=@DataSetID) SET @countHistorical=(SELECT COUNT(1) from tblOptyRecordsHistorical where DataSetID=@DataSetID) IF @destination='C BEGIN if @countCurrent> BEGIN RAISERROR('There are already existing records in the Current Tables for the specified DataSet',5、1) END ELSE if @countHistorical= BEGIN RAISERROR('There do not appear to be any records in the Historical Tables to transfer for the specified Dataset',5、1) END ELSE BEGIN -- ENTER TRANSFER CODE INSERT INTO tblRecordsHistorical X,Y,Z ) SELECT X,Y,Z FROM tblA WHERE x=y -- Check that record count in both tables match SET @countCurrent=(SELECT COUNT(1) from tblOptyRecordsCurrent where DataSetID=@DataSetID) SET @countHistorical=(SELECT COUNT(1) from tblOptyRecordsHistorical where DataSetID=@DataSetID) IF (@countCurrent@countHistorical) BEGIN RAISERROR('There was an error whilst copying the records into the Historical Tables,Source and Destination Record Count do not match5、1) END ELSE BEGIN END END END ELSE IF @Destination='H BEGIN if @countHistorical> BEGIN RAISERROR('There are already existing records in the Historical Tables for the specified DataSet5、1) END ELSE if @countCurrent= BEGIN RAISERROR('There do not appear to be any records in the Historical Tables to transfer for the specified Dataset',5、1) END ELSE BEGIN RAISERROR('DataSet Found,ready to transfer records to HISTORICAL',5、1) -- ENTER TRANSFER CODE INSERT INTO tblOptyRecordsCurrent X,Y,Z ) SELECT X,Y,Z FROM tblB WHERE x=y -- Check that record count in both tables match SET @countCurrent=(SELECT COUNT(1) from tblOptyRecordsCurrent where DataSetID=@DataSetID) SET @countHistorical=(SELECT COUNT(1) from tblOptyRecordsHistorical where DataSetID=@DataSetID) END END END ELSE BEGIN RAISERROR('The DataSet you have specified cannot be found',5、1) END END ELSE BEGIN RAISERROR('You have not specified a valid Destination5、1) END请注意,包括在内INSERT INTO在代码的两部分中,至少会有两个额外的部分SQL Action他们必须全部工作或失败。
5 t5 B, {) V+ b2 y; V编辑:我已经和了
$ ~. G8 R; `. Y6 D- L# F! iBEGIN TRANBEGIN TRY -- STATEMENT 1 INSERT INTO X WHERE Y -- STATEMENT 2 DELETE FROM X WHERE Y -- STATEMENT 3 UPDATE X WHERE Y COMMITEND TRYBEGIN CATCH ROLLBACK TRAN RAISERROR('There was an error whilst copying the records into the Current Tables. The Transaction has been rolled back',5,1)END CATCH ' V6 b. l9 e* F, |: e
解决方案: |
|