SQL Server:預存程序中編寫交易處理的方法小結

來源:互聯網
上載者:User

標籤:sql

/**8. SQLServer預存程序中編寫交易處理的方法小結**/

原文出處: http://www.jb51.net/article/80636.htm

本文我們介紹了三種不同的方法,舉例說明了如何在預存程序交易處理中編寫正確的代碼。

1. 常見寫法:

在編寫SQL Server 事務相關的預存程序代碼時,經常看到下面這樣的寫法:

begin tran

update statement 1 ...

update statement 2 ...

delete statement 3 ...

commit tran

 

2. 存在的問題/隱患:

執行時會出現一個違反not null 約束的錯誤資訊,但隨後又提示(1 row(s) affected)。我們執行select* from demo 後發現insert into demo values(2) 卻執行成功了。這是什麼原因呢? 原來 SQL Server在發生runtime 錯誤時,預設會rollback引起錯誤的語句,而繼續執行後續語句。

create table demo(id int notnull)

go

begin tran

insert into demo values (null)

insert into demo values (2)

commit tran

go

3. 如何避免這樣的問題呢?有三種方法:

方法1. 在事務語句最前面加上set xact_abort on;當xact_abort 選項為on 時,SQLServer在遇到錯誤時會終止執行並rollback 整個事務。

setxact_abort on

begintran

updatestatement 1 ...

updatestatement 2 ...

deletestatement 3 ...

committran

go

方法2. 在每個單獨的DML語句執行後,立即判斷執行狀態,並做相應處理。

begintran

updatestatement 1 ...

if @@error <>0

beginrollbacktran

gotolabend

end

deletestatement 2 ...

if @@error <> 0

beginrollbacktran

gotolabend

end

committran

labend:

go

方法3. 在SQL Server 2005中,可利用 try...catch 異常處理機制。

begintran

begintry

updatestatement 1 ...

deletestatement 2 ...

endtry

begincatch

if @@trancount >0

rollbacktran

endcatch

if @@trancount >0

committran

go

 

4. 示範:下面是個簡單的預存程序,示範交易處理過程。

--set nocount on 表示不返回計數

create procedure dbo.pr_tran_inprocas 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

 

執行:

Exec dbo.pr_tran_inproc


本文出自 “Ricky's Blog” 部落格,請務必保留此出處http://57388.blog.51cto.com/47388/1772724

SQL Server:預存程序中編寫交易處理的方法小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.