1. 程式人生 > 實用技巧 >SQL SERVER 事務的使用(tran)

SQL SERVER 事務的使用(tran)

SQL SERVER 事務的使用(tran)

--建立一個表,設定一個欄位不為空
create table Student(Name nvarchar(20) not null)

Num One:--當操作(增刪改)是由null引發的錯誤時,事務會跳過錯誤繼續執行正常的語句。

begin tran
   insert into Student(Name) values (null)
   insert into Student(Name) values ('bob')
   insert into Student(Name) values (null)
commit tran

--【方法 一】:當操作(增刪改)是由null引發的錯誤時,@@ERROR<>0 事務遇到錯誤就不會繼續執行,全部不會寫入

begin tran    
   insert into Student(Name) values (null)
   insert into Student(Name) values ('666')
   insert into Student(Name) values (null)

   if @@ERROR>0 --
      begin
        rollback tran 
        return
      end
commit tran

--【方法 二】:xact_abort on/off on:開啟,事務一旦出問題,全部回滾 off:關閉,不檢查事務是否發生錯誤。


abort:中止 xact(沒查出來啥意思)

set xact_abort on --如果是off,那麼符合條件的會寫入,異常的不會寫入
begin tran
   insert into Student(Name) values (null)
   insert into Student(Name) values ('xact_abort')
   insert into Student(Name) values (null) 
commit

--【方法三】:try catch

begin tran   
      begin try
           insert
into Student(Name) values ('try catch') insert into Student(Name) values ('try catch') insert into Student(Name) values (null) end try begin catch if @@TRANCOUNT>0 rollback tran end catch if @@TRANCOUNT>0 commit tran --在SqlServer裡,巢狀事務的層次是由@@TranCount全域性變數反映出來的。 --每一次Begin Transaction都會引起@@TranCount加1。 --每一次Commit Transaction都會使@@TranCount減1, --RollBack Transaction會回滾所有的巢狀事務包括已經提交的事務和未提交的事務, --而使@@TranCount置0 --so 如果@@TRANCOUNT>0的話 那就是有begin tran有提交 --如果有異常,就進到catch裡,然後@@TRANCOUNT又是大於0的,就是會全部回滾 --沒有catch中,那 就是全部提交

--【方法四】:save transaction

begin transaction tran_A -- 最好是為事務定義一個名字。
    insert into Student(Name) values ('save transaction4')
       insert into Student(Name) values (null)
    save transaction save_tran; --定義一個事務的儲存點、當要回滾事務時,可以回滾到這裡。

rollback transaction save_tran;--回滾事務到儲存點
commit transaction tran_A;-- 提交事務。

網上的一個老哥的Code

begin transaction tran_A -- 最好是為事務定義一個名字。

    insert into Nums(X) values(9);
    save transaction save_tran; --定義一個事務的儲存點、當要回滾事務時,可以回滾到這裡。
    insert into Nums(X) values(4),(3),(2),(1);
    rollback transaction save_tran;--回滾事務到儲存點

commit transaction tran_A;-- 提交事務。