遊標代碼舉例
來源:互聯網
上載者:User
遊標
1.對低於當前平均價格的書,均提價50%
2對於高於或等於當前平均價格的書,均降價25%
代碼如下:
declare title_update cursor
for select title_id,price from titles
for update
go
局部變數
declare @avg_price money,@title_id tid,@price money
open title_update
begin tran
計算平均書價
select @avg_price=avg(price) from titles holdlock
fetch title_update into @title_id,@price
while @@sqlstatus!=2
begin
if @@sqlstatus=1
begin
rollback tran
raiserror 21001 "Fetch failed in cursor"
close title_update
deallocate cursor title_update
return
end
if @price<@avg_price
提價50%
update titles set price = price * $1.50
where current of title_update
else
降價25%
update titles set price = price * $.75
where current of title_update
if @@error!=0
begin
rollback tran
raiserror 22001 "Update failed"
close title_update
deallocate cursor title_update
return
end
fetch title_update into @title_id,@price
end
commit
close title_update
deallocate cursor title_update
go