SqlServer try catch 捕獲觸發器\存儲過程異常,結合 transaction 事務


SoEasy~,貼上代碼看所有

 1 ALTER trigger [dbo].[tgr_SG_Gathering_update]
 2 on [dbo].[SG_Gathering]
 3     for update --更新觸發
 4 as
 5     --定義變量
 6     declare @fMoney float,
 7     @fQuantity float,
 8     @vShop varchar(20),
 9     @vEmpCode varchar(20),
10     @vSPosition varchar(20),
11     @vSPCode varchar(20),
12     @SetID int,
13     @Amount float,
14     @Coupon varchar(20),
15     @RJ varchar(10),
16     @DiscountNum int;
17 
18     begin try
19         begin transaction
20             if (update(bCancel)) --bCancel日結動作
21                 begin
22                     --變量取值
23                     select @RJ=bTotal,@fMoney=fMoney,@vShop=vShop,@vEmpCode=vEmpCode,@vSPCode=vSPCode,@fQuantity=fQuantity,@vSPosition=vSPosition 
24                     from inserted;
25 
26                     INSERT INTO [NoahERP].dbo.DiscountCouponPool( SetID,Coupon,CardType,Type,PP,MadeType,Rate,Price,Amount,StartDate,EndDate,
27                                 CreateDate,UseDate,ModifyPerson,IsDel,ImgUrl,UsedImgUrl,OverImgUrl,ClothesCounts) 
28                         SELECT  S.ID,@Coupon,S.CardType,S.[Type],S.[PP],S.MadeType,P.Rate,P.Price,S.Amount,S.StartDate,S.EndDate,
29                                 GETDATE(),NULL,'',0,P.ImgUrl,P.UsedImgUrl,P.OverImgUrl,S.ClothesCounts 
30                                 FROM [NoahERP].[dbo].[DiscountCouponSet] S 
31                                 left join  NoahERP.dbo.DiscountCouponPrice P on S.ID=P.SetID 
32                                 where  CONVERT(date, GETDATE()) >= CONVERT(date,S.StartDate) AND DATEADD(DAY,-1,CONVERT(DATE,GETDATE())) < CONVERT(date,S.EndDate)  
33                                 AND  S.IsStop = 0 And S.Type=1  AND S.ID=@SetID;
34                 end
35         commit transaction    --提交事務
36     end try
37     begin catch
38 
39     if(@@TRANCOUNT>0)
40         begin
41             rollback transaction;--出現錯誤回滾
42         end
43     --記錄錯誤信息到[SG_GatheringLog]表
44     insert into [dbo].[SG_GatheringLog](ErrorNumber,
45                                         ErrorSeverity,
46                                         ErrorState,
47                                         ErrorProcedure,
48                                         ErrorLine,
49                                         ErrorMessage)
50     select ERROR_NUMBER()  ErrorNumber,            --返回導致運行 CATCH 塊的錯誤消息的錯誤號
51            ERROR_SEVERITY()  ErrorSeverity,        --返回導致 CATCH 塊運行的錯誤消息的嚴重級別
52            ERROR_STATE()  ErrorState,            --返回導致 CATCH 塊運行的錯誤消息的狀態號
53            ERROR_PROCEDURE()  ErrorProcedure,    --返回出現錯誤的存儲過程或觸發器名稱
54            ERROR_LINE()  ErrorLine,                --返回發生錯誤的行號
55            ERROR_MESSAGE()  ErrorMessage        --返回導致 CATCH 塊運行的錯誤消息的完整文本
56     end catch


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM