2014-12-09 134 views
0

我有8個表。一位家長和7個孩子。在while循環內部並逐個從表中刪除。 如果循環過程中發生任何錯誤,則返回所有事務。是否有可能在while循環中。在while循環內處理錯誤

實施例:

申報@count INT,@intFlag INT

開始嘗試 組@count =(SELECT COUNT(ID)從MyTable的其中[日期] GETDATE() - 1之間和GETDATE( )) 如果@count> 0

開始 組@intFlag = 1

開始事務

while (@intFlag <= @Count) 
begin 

    update MyTable1 
     set column1 = 1 
    where [Date] between getdate()-1 and getdate(); 

    update MyTable2 
     set column2 = 1 
    where [Date] between getdate()-1 and getdate(); 

set @intFlag = @intFlag + 1 
end; 

提交

末嘗試

開始抓 如果@@ TRANCOUNT> 0回滾 端部鉤掛

如果處理其回滾所有子表中的任何錯誤交易

+0

在循環之前啓動事務。 如果您可以使用try-catch來檢測錯誤,請在try塊結束時使用commit事務在try-catch塊中放置循環,並在catch塊內回滾 – Sach 2014-12-09 12:37:01

回答

0

嘗試捕捉塊上方的循環如下

BEGIN TRANSACTION 

BEGIN TRY 

/* 
* YOUR LOOP 
*/ 

COMMIT TRANSACTION 
END TRY 
BEGIN CATCH 

ROLLBACK TRANSACTION 

END CATCH