2017-06-19 73 views
0

假設我有一個光標,其找到數據來更新,SQL服務器運行光標兩次

declare @index int; 
declare cursor1 cursor for 
select table1_index from table where (table1_date < dateadd(dd, -365, getdate())) 

open cursor1 
fetch next from cursor1 into @index 
while @@fetch_status = 0 
begin 
    update table1 
    set table1_field = SOMETHING 
    where table1_index = @index 

    if @ERROR = 0 
    insert into audit_trail 
    values(getdate(), table1_index) 

    fetch next from cursor1 into @index 
end 
close cursor1 
deallocate cursor1 

上面的代碼是在存儲過程中,將被調度的日常(爲上午12點的日常實例跑出)。

我的問題是,如果調度程序運行存儲的專業版。 (例如,17/06/2017 12:00 AM),並且仍在運行(例如在2017年6月17日05:00 PM)。

如果我運行完全相同的代碼(例如17/06/2017 03:00 PM), 將光標從更新的表中選擇數據?或來自調度程序未更新的表的數據?

非常感謝。

+0

取決於您的交易模式,但假定ACID合規模式和交易邊界在程序之外:它將使用第一個程序開始運行之前的數據。 –

+0

由於您正在進行隱式事務處理,整個更新語句可能會阻止對該表的進一步更新,並且17/06/2017 03:00 PM將等待UPDATE語句完成。由於這是一個巨大的UPDATE語句,它將成爲表鎖或頁鎖,並且它將阻塞其他事務,直到它完成。 –

+0

我的更新語句似乎不是很大,不會花費太多時間來執行。無論如何,謝謝你的回答:)。 – ProgrammingBaKa

回答

1
declare cursor1 cursor for 
select table1_index from table where (table1_date < dateadd(dd, -365, getdate())) 
and table1_index NOT IN (SELECT table1_index FROM audit_trail) 

您需要添加條件and table1_index NOT IN (SELECT table1_index FROM audit_trail)。我希望它能爲你工作。