SQL Server存儲過程中編寫事務(wù)處理的方法小結(jié)
本文實(shí)例講述了SQL Server存儲過程中編寫事務(wù)處理的方法。分享給大家供大家參考,具體如下:
SQL Server中數(shù)據(jù)庫事務(wù)處理是相當(dāng)有用的,鑒于很多SQL初學(xué)者編寫的事務(wù)處理代碼存往往存在漏洞,本文我們介紹了三種不同的方法,舉例說明了如何在存儲過程事務(wù)處理中編寫正確的代碼。希望能夠?qū)δ兴鶐椭?/p>
在編寫SQL Server 事務(wù)相關(guān)的存儲過程代碼時,經(jīng)??吹较旅孢@樣的寫法:
begin tran update statement 1 ... update statement 2 ... delete statement 3 ... commit tran
這樣編寫的SQL存在很大隱患。請看下面的例子:
create table demo(id int not null) go begin tran insert into demo values (null) insert into demo values (2) commit tran go
執(zhí)行時會出現(xiàn)一個違反not null 約束的錯誤信息,但隨后又提示(1 row(s) affected)。 我們執(zhí)行select * from demo 后發(fā)現(xiàn)insert into demo values(2) 卻執(zhí)行成功了。 這是什么原因呢? 原來 SQL Server在發(fā)生runtime 錯誤時,默認(rèn)會rollback引起錯誤的語句,而繼續(xù)執(zhí)行后續(xù)語句。
如何避免這樣的問題呢?有三種方法:
1. 在事務(wù)語句最前面加上set xact_abort on
set xact_abort on begin tran update statement 1 ... update statement 2 ... delete statement 3 ... commit tran go
當(dāng)xact_abort 選項為on 時,SQL Server在遇到錯誤時會終止執(zhí)行并rollback 整個事務(wù)。
2. 在每個單獨(dú)的DML語句執(zhí)行后,立即判斷執(zhí)行狀態(tài),并做相應(yīng)處理。
begin tran update statement 1 ... if @@error <> 0 begin rollback tran goto labend end delete statement 2 ... if @@error <> 0 begin rollback tran goto labend end commit tran labend: go
3. 在SQL Server 2005中,可利用 try...catch 異常處理機(jī)制。
begin tran begin try update statement 1 ... delete statement 2 ... endtry begin catch if @@trancount > 0 rollback tran end catch if @@trancount > 0 commit tran go
下面是個簡單的存儲過程,演示事務(wù)處理過程。
create procedure dbo.pr_tran_inproc as begin set nocount on begin tran update statement 1 ... if @@error <> 0 begin rollback tran return -1 end delete statement 2 ... if @@error <> 0 begin rollback tran return -1 end commit tran return 0 end go
希望本文所述對大家SQL Server數(shù)據(jù)庫程序設(shè)計有所幫助。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。