在存儲過程中編寫正確的事務處理代碼(SQL Server 2000 & 2005)

在 SQL Server 中數據庫事務處理是個重要的概念,也稍微有些不容易理解,很多 SQL 初學者編寫的事務處理代碼存往往存在漏洞,本文介紹了三種不同的方法,舉例說明了如何在存儲過程事務處理中編寫正確的代碼。

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

      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

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

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

1. 在事務語句最前面加上set xact_abort on

   set xact_abort on

   begin tran
      update statement 1 ...
      update statement 2 ...
      delete statement 3 ...
   commit tran
   go

當 xact_abort 選項爲 on 時,sql server 在遇到錯誤時會終止執行並 rollback 整個事務。

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

   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 異常處理機制

   begin tran

   begin try
      update statement 1 ...
      delete statement 2 ...
   end try
   begin catch
      if @@trancount > 0
         rollback tran
   end catch

   if @@trancount > 0
      commit tran
   go

下面是個簡單的存儲過程,演示事務處理過程。

   create procedure dbo.pr_tran_inproc
   as
   begin
      set nocount on

      begin TRANSACTION
      begin try
         SQL腳本。。。。
      end try
      begin catch
      if @@trancount > 0
         rollback TRANSACTION
      end catch
      if @@trancount > 0
      commit TRANSACTION 
  end
發佈了54 篇原創文章 · 獲贊 6 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章