遊標是什麼
遊標是SQL 的一種數據訪問機制。可以將遊標簡單的看成是查詢的結果集的一個指針,可以根據需要在結果集上面來回滾動,瀏覽需要的數據。
爲什麼要使用遊標
遊標一般用於把通過腳本得到的結果集的內容在用於其它的SQL語句中。或者是當你需要對select出來的結果循環處來理的時候就需要用到遊標。
遊標的生命週期
遊標的生命週期包含有五個階段:聲明遊標、打開遊標、讀取遊標數據、關閉遊標、釋放遊標。
怎麼使用遊標
book表
--定義遊標
declare cur_set_levers CURSOR
for select id, Price from books
--打開遊標
open cur_set_levers
declare @id int
declare @price decimal(18,2)
fetch next from cur_set_levers into @id,@price --將遊標向下移1行,獲取的數據放入之前定義的變量@id,@price中
print @id
--循環獲取
while(@@FETCH_STATUS=0)--讀取數據是否成功
begin
print @id
if(@price<50)
update books set Levels='便宜' where id=@id
else if(@price<100)
update books set Levels='中等' where id=@id
else
update books set Levels='貴' where id=@id
fetch next from cur_set_levers into @id,@price --將遊標向下移1行,獲取的數據放入之前定義的變量@id,@price中
end
close cur_set_levers --關閉遊標
deallocate cur_set_levers --釋放遊標
執行之後
總結
遊標雖然能很方便的處理select出來的結果,但是遊標執行會影響腳本執行速度,佔用內存十分高,容易造成內存泄露。