2012-03-02 84 views
2

假設我正在處理10張圖書卡,每張卡片都有客戶價值(例如會員編號,會員姓名......),我需要爲每張卡片更新一個值。SYBASE中的遊標的替代方法?

如果我想從數據庫中抓取所有十個,但只想每次更新一行,是否有光標的替代?我知道一個while循環可能會工作,但是如何才能在每次循環時抓取一行,直到完成所有10張卡?

+0

爲什麼你不能只用一條更新語句來一次更新它們? – 2012-03-02 20:38:21

+0

是的,我想到了這個選擇,但每次更新任何行時,它都會獲得自己的事務號更新。我無法使用相同的交易號碼更新全部10個。 – James 2012-03-02 20:50:47

回答

8

不需要使用遊標。我大部分時間都在使用它:

declare @uid int -- this is the type unique index on the table you're updating 

-- Copy out the unique ids of the rows you want to update to a temporary table 
select uid into #temp from customers -- you can use a where condition here 

-- Loop through the rows of the temp table 
while exists (select 1 from #temp) 
begin 
    set rowcount 1 
    select @uid = uid from #temp -- pull one uid from the temp table 
    set rowcount 0 
    delete from #temp where uid = @uid -- delete that uid from the temp table 

    -- Do something with the uid you have 
    update customers set name = 'Joe Shmoe' where uid = @uid 

end 
0

可以使用特定列上的聚簇索引在表上循環。由於聚集索引按排序順序排列行,因此它可以像循環的索引變量一樣使用。

declare @uid int 
select @uid = 0 -- assume the uids in table are > 0 
declare @rowsaf int 
select @rowsaf = 1 

while @rowsaf > 1 
begin 
    set rowcount 1 
    select @uid = uid from customers where uid > @uid 
    select @rowsaf = @@rowcount 

    -- update the row using @uid 
end 

set rowcount 0 

Here is the article對此有詳細解釋。