/ / Alternatywa dla kursorów w SYBASE? - sql, sybase

Alternatywa dla kursorów w SYBASE? - sql, sybase

Powiedzmy, że mam do czynienia z 10 kartami bibliotecznymi, każda karta ma wartości klienta (np. Numer członka, nazwa członka ...) i muszę zaktualizować wartość dla każdej karty.

Jeśli chcę pobrać wszystkie dziesięć z bazy danych, alechcesz aktualizować każdy wiersz pojedynczo, czy istnieje alternatywa dla kursora? Wiem, że pętla while może zadziałać, ale jak mógłbym chwycić jeden wiersz za każdym razem, gdy zapętli, aż skończyłem ze wszystkimi 10 kartami?

Odpowiedzi:

8 dla odpowiedzi № 1

Nie musisz używać kursorów. Używam tego najczęściej:

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 dla odpowiedzi nr 2

Możliwe jest zapętlenie w tabeli przy użyciu indeksu klastrowego w określonej kolumnie. Ponieważ indeks klastrowany porządkuje wiersze w porządku posortowanym, może być użyty jako zmienna indeksowa pętli.

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

Oto artykuł to wyjaśnia to szczegółowo.