2012-03-02 48 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对此有详细解释。