先來看一個(gè)概念:
數(shù)據(jù)庫事務(wù)(Database Transaction) ,是指作為單個(gè)邏輯工作單元執(zhí)行的一系列操作,要么完整地執(zhí)行,要么完全地不執(zhí)行。那么在存儲(chǔ)過程里添加事務(wù),則可以保證該事務(wù)里的所有sql代碼要么完全執(zhí)行要么完全不執(zhí)行。
舉個(gè)簡單的帶事務(wù)的存儲(chǔ)過程:
?12345678910111213141516171819 BeginSet NOCOUNT ON; --不返回影響行數(shù) Set XACT_ABORT ON; --使用存儲(chǔ)過程執(zhí)行事務(wù)需要開啟XACT_ABORT參數(shù)(默認(rèn)為OFF) delete from table1 where name='' --刪除數(shù)據(jù)sql1 begin tran tran1 --開始一個(gè)事務(wù)tran1 delete from table1 where name='' --刪除數(shù)據(jù)sql2 save tran tran2 --保存一個(gè)事務(wù)點(diǎn)tran2 update table2 set name='' where id='' --修改數(shù)據(jù)sql3 if @@error<>0 --判斷修改數(shù)據(jù)有沒有錯(cuò)誤(@@error表示返回與@@ERROR 最近的語句(即sql3)的非零的錯(cuò)誤碼,沒有錯(cuò)誤則返回0) beginrollback tran tran2 --回滾事務(wù)到tran2的還原點(diǎn) commit tran tran1 --提交事務(wù)tran1 endelse --沒有出錯(cuò)則提交事務(wù)tran1 commit tran tran1 --提交事務(wù)tran1 End
如果sql3執(zhí)行失敗,則會(huì)回滾到事務(wù)tran2的創(chuàng)建處(相當(dāng)于出來sql1和sql2執(zhí)行外都未執(zhí)行)。
更多信息請查看IT技術(shù)專欄