SQL Server 游標的使用

2021-10-04 14:16:19 字數 3084 閱讀 4273

一、sql server 游標的簡單使用

乙個對錶進行操作的t-sql語句通常都可產生或處理一組記錄,但是許多應用程式,尤其是t-sql嵌入的主語言,通常不能把整個結果集作為乙個單元來處理,這些應用程式就需要用一種機制來保證每次處理結果集中的一行或幾行,游標(cursor)就提供了這種機制。

sql server對游標的使用要遵循:宣告游標–開啟游標–讀取資料–關閉游標–刪除游標。下面讓我們來看看幾種常用游標是怎麼使用的!

1、唯讀游標的使用(只能使用next提取資料)

--宣告乙個唯讀游標

declare cur_stu cursor

forselect sno as '學號',sname as '姓名' from stu where mno in(select mno from major where mname=

'計算機工程'

)for

read only

--開啟游標

open cur_stu

--讀取資料

--根據fetch的狀態值讀取資料,0表示執行成功

-- -1表示所要讀取的資料不在結果集中

-- -2表示被提取的行已不存在

while @@fetch_status=0

begin

fetch next from cur_stu

end--關閉游標

close cur_stu

--刪除游標

deallocate cur_stu

2、動態游標的使用

--宣告乙個動態游標

declare cur_stu cursor dynamic

forselect sno as '學號',sname as '姓名' from stu

--開啟游標

open cur_stu

--從游標cur_stu中提取第一行資料

fetch first from cur_stu

--從游標cur_stu中提取下一行資料

fetch next from cur_stu

--從游標cur_stu中提取上一行資料

fetch prior from cur_stu

--從游標cur_stu中提取最後一行資料

fetch last from cur_stu

--從游標cur_stu中提取當前行的下兩行記錄

fetch relative 2 from cur_stu

--從游標cur_stu中提取當前行的上兩行記錄

fetch relative -2 from cur_stu

--關閉游標

close cur_stu

--刪除游標

deallocate cur_stu

3、使用游標更新表中某個字段例:對sc表(學生選課表)新增乙個等級列(rank),若學生成績80及以上等級a,70-79分 為b,其餘為c

--定義乙個動態游標

declare sc_cur cursor dynamic

forselect sno,cno,grade from sc

declare @xh char(4)

declare @kch char(4)

declare @cj numeric(6,1)

declare @dj char(1)

--開啟游標

open sc_cur

--根據fetch的狀態值讀取資料,0表示執行成功

-- -1表示所要讀取的資料不在結果集中

-- -2表示被提取的行已不存在

while @@fetch_status=0

begin

fetch next from sc_cur into @xh,@kch,@cj

if @cj >=80

set @dj=

'a'if @cj <80 and @cj>=70

set @dj=

'b'if @cj<70 or @cj is null

set @dj=

'c'update sc set rank = @dj where sno=@xh and cno=@kch

endgo

--關閉游標

close sc_cur

--刪除游標

deallocate sc_cur

執行後的結果

4、游標變數與儲存過程結合使用

例:建立乙個儲存過程,通過輸入乙個學生的學號,通過輸出引數返 回該學生所有選修課程的成績

create procedure pro_grade @xh char(4), 

@cur_grade cursor varying output

as--forward_only游標只能從第一行滾動到最後一行,只支援fetch的next提取選項

set @cur_grade = cursor forward_only for

select sno,cno,grade from sc where sno=@xh

--開啟游標

open @cur_grade

go--宣告乙個游標變數

declare @my_cur cursor

--執行儲存過程

exec pro_grade @xh=

's001', @cur_grade=@my_cur output

--讀取資料

while @@fetch_status=0

begin

fetch next from @my_cur

end--關閉游標

close @my_cur

--刪除游標

deallocate @my_cur

執行後的結果

SQL Server游標的使用

declare cursor name cursor local global forward only scroll static keyset dynamic fast forward read only scroll locks optimistic type warning for sele...

SQL Server游標的使用

由於sql server中沒有提供直接遍歷表的每一行的方法,所以只有通過游標和while迴圈來代替。當讓也可以不適用游標,僅僅使用while迴圈也能遍歷表 當id為int,主鍵時可用這種方式 但兩種方式我沒有做過實際的對比測試,效率誰高誰低我也不好說。我只給乙個游標使用的簡單示例,想深入了解和使用游...

SQL SERVER 游標的使用

定義游標,讓游標指向sql查詢的結果 declare democursor cursor for select name,id from userinfo 開啟游標。open democursor declare name nvarchar 32 declare id int 把游標指向的資料取出來...