2012-03-02 6 views
2

私は10枚のライブラリカードを扱っていますが、各カードには顧客の価値(メンバー番号、メンバー名など)があり、各カードの値を更新する必要があります。SYBASEのカーソルの代わりに?

データベースから10個すべてを取得したいが、各行を一度に1つだけ更新したい場合は、カーソルの代替方法がありますか?私はループがうまくいくかも知っていますが、ループするたびに1つの行を取得して、10枚のカードすべてで終わるまではどうしますか?

+0

更新ステートメントを使用してすべてを一度に更新することができない理由は何ですか? –

+0

はい、私はそのオプションを考えましたが、私はすべての行を更新するたびに、独自のトランザクション番号も更新されます。同じ取引番号で10をすべて更新することはできません。 – James

答えて

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詳細に説明します。

関連する問題