Sql Server 遊標筆記

1.定義

遊標是SQL 的一種數據訪問機制。可以將遊標簡單的看成是查詢的結果集的一個指針,可以根據需要在結果集上面來回滾動,瀏覽需要的數據。

2. 使用遊標

--聲明遊標
declare cur_cust_level Cursor
for select id,ConsumeAmount from Customers


--打開遊標
open cur_cust_level
--瀏覽數據,取數據ID,ConsumeAmount

--取數據
declare @id int 
declare @Cacount int
fetch next from cur_cust_level into @id,@Cacount

--循環往下
while (@@FETCH_STATUS=0)

begin
 --修改消費等級
 if(@Cacount<500)
update Customers set ConsumeLeve='低消費' where id=@id
else if(@cacount <1000)
update Customers set ConsumeLeve='中消費' where id=@id
else
update Customers set ConsumeLeve='高消費' where id=@id
fetch next from cur_cust_level into @id,@cacount
end

--關閉遊標
close cur_cust_level

--釋放遊標
deallocate cur_cust_level
select *from Customers
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章