首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SYBASE中游标的替代方案?

SYBASE中游标的替代方案?
EN

Stack Overflow用户
提问于 2012-03-03 04:29:50
回答 2查看 13.8K关注 0票数 2

假设我正在处理10张借书卡,每张卡都有客户价值(例如:会员编号、会员名称...)我需要为每张卡更新一个值。

如果我想从数据库中获取全部10个数据,但每次只更新一行,那么有没有替代游标的方法呢?我知道while循环可能会起作用,但我如何能够在每次循环时都抓取一行,直到我处理完所有10张牌?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-03 04:43:12

不需要使用游标。我大部分时间都在用这个:

代码语言:javascript
复制
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
票数 9
EN

Stack Overflow用户

发布于 2013-05-26 00:45:59

可以使用特定列上的聚集索引对表进行循环。因为聚集索引按排序顺序排列行,所以它可以像循环的索引变量一样使用。

代码语言:javascript
复制
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详细解释了这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9539918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档