【问题标题】:Alternative to cursors in SYBASE?SYBASE 中游标的替代方案?
【发布时间】:2013-05-26 00:45:59
【问题描述】:

假设我要处理 10 张借书卡,每张卡都有客户值(例如会员编号、会员姓名……),我需要更新每张卡的值。

如果我想从数据库中获取所有十个但只想一次更新每一行,是否有替代游标的方法?我知道 while 循环可能会起作用,但我如何能够在每次循环时抓取一行,直到我用完所有 10 张卡片?

【问题讨论】:

  • 有什么理由不能只使用更新语句一次更新它们?
  • 是的,我已经想到了这个选项,但是每次我更新任何行时,它都会更新它自己的事务号。我无法使用相同的交易号更新所有 10 个。

标签: sql sybase


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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详细解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多