尽管我宣称它为"更新",Cursor仍然只读它

Sco*_*ain 3 sql sql-server sql-server-2008

我正在尝试更新游标内的一行.我要做的是用OLD_QTY和NEW_QTY更新记录链.但是,当我尝试进行更新时,The cursor is READ ONLY即使我包含for update of OLD_QTY, NEW_QTY在我的declration中,也会出现错误.如果我在select语句中包含OLD_QTY和没有区别NEW_QTY.

declare @current_inv_guid uniqueidentifier
declare @last_inv_guid uniqueidentifier
declare @current_vid int
declare @last_vid int
--declare @current_new_qty money
declare @last_new_qty money
--declare @current_old_qty money

declare iaCursor cursor 
      for select INV_GUID, old_VID
          --, OLD_QTY, NEW_QTY  
          from #IA 
          order by INV_GUID, old_vid, ENTRY_NUM 
      for update --of OLD_QTY, NEW_QTY
open iaCursor
Fetch next from iaCursor into @current_inv_guid, @current_vid --, @current_old_qty, @current_new_qty

while @@fetch_status = 0
begin
    --test to see if we hit a new chain.
    if(@last_inv_guid <> @current_inv_guid or @current_vid <> @last_vid)
    begin
        set @last_new_QTY = (select #lots.QTY_RECEIVED from #lots where #lots.INV_GUID = @current_inv_guid and LOT_VID = @current_vid)
        set @last_inv_guid = @current_inv_guid
        set @last_vid = @current_vid    
    end

    --update the current link in the chain
    update #ia
        set OLD_QTY = @last_new_QTY,
            NEW_QTY = @last_new_QTY + QTY_CHANGE,
            @last_new_QTY = @last_new_QTY + QTY_CHANGE
        where current of iaCursor

    --get the next link
    fetch next from iaCursor into @current_inv_guid, @current_vid --, @current_old_qty, @current_new_qty
end 

close iaCursor
deallocate iaCursor
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 8

把一个order by在select取得光标只读.


GSe*_*erg 8

您没有明确说明您想要的行为,因此,默认规则适用,根据该规则,游标可能是可更新的,也可能不是可更新的,具体取决于基础查询.

order by在可更新的游标中使用它是完全正常的,但你必须更详细并告诉SQL Server你想要的细节,例如:

declare iaCursor cursor
local
forward_only
keyset
scroll_locks
for
  select INV_GUID, old_VID
  from #IA 
  order by INV_GUID, old_vid, ENTRY_NUM 
for update of OLD_QTY, NEW_QTY
Run Code Online (Sandbox Code Playgroud)


Kar*_*und 5

Patrick列出的文档页面上有一个重要的提示但很细微:

如果查询引用了至少一个没有唯一索引的表,则键集游标将转换为静态游标。

当然,STATIC游标是只读的。