SQL中的游標

2021-08-05 23:48:06 字數 2060 閱讀 4496

什麼叫游標(cursor)

乙個游標(cursor)可以被看作指向結果集(a set of rows)中一行的指標(pointer)。

游標每個時間點只能指向一行,但是可以根據需要指向結果集中其他的行。

例如:select * from employees where ***=』m』會返回所有性別為男的雇員,在初始的時候,游標被放置在結果集中第一行的前面。

使游標指向第一行,要執行fetch。當游標指向結果集中一行的時候,可以對這行資料進行加工處理,要想得到下一行資料,要繼續執行fetch。fetch操作可以重複執行,直到完成結果集中的所有行。

什麼時候使用游標?
簡單的回答是需要對選出的結果集,進行遍歷的時候,需要考慮使用游標。

當需要在儲存過程中遍歷所查得的結果集時用游標

1。在儲存過程中,使游標,可以根據每條記錄的某個欄位的取值的不同,來採取相應的處理。這就是流程控制。

2. 游標的乙個常見用途就是儲存查詢結果,以便以後使用。游標的結果集是由select語句產生,如果處理過程需要重複使用乙個記錄集,那麼建立一次游標而重複使用若干次,比重複查詢資料庫要快的多。

游標的使用方法
declare @id

intdeclare @oid

intdeclare @login varchar(50)

--定義乙個游標

declare user_cur cursor for

select id,oid,[login] from st_user

--開啟游標

open user_cur

while

@@fetch_status=0 請輸入**

begin

--讀取游標

fetch next from user_cur into @id,@oid,@login

print

@id

--print

@login

endclose user_cur

--摧毀游標

deallocate user_cur

例子

建立乙個儲存過程使用游標 如果該職工入職時間超過3年 並且學歷 在本科以上 則對該職工工資加10%如果 學歷沒達到本科的 入職時間在10年以上 同樣對該職工工資追加8% 其他的一律不加

reate proc jiagongzi

asdeclare @name nvarchar(20)

declare @xueli nvarchar(20)

declare @time datetime

declare @gongzi intdeclare zengjia cursor scroll

forselect * from 職員表

open zengjia

fetch next from zengjia into @name,@xueli,@time,@gongzi

while

@@fetch_status=0

begin

if (@xueli='本科'

or@xueli='碩士') and

datediff(year, @time, getdate())>=3

begin

update 職員表 set 工資=@gongzi+@gongzi*0.1 where 姓名=@name

endif (@xueli

<>'本科'

and@xueli

<>'碩士') and

datediff(year, @time, getdate())>=10

begin

update 職員表 set 工資=@gongzi+@gongzi*0.08 where 姓名=@name

end fetch next from zengjia into @name,@xueli,@time,@gongzi

endclose zengjia

deallocate zengjia goexec jiagongzi

SQL 中的游標例項

宣告變數 declare imtype varchar 10 imresourceid varchar 10 定義游標 declare information cursor cursor for select imtype imresourceid from bjyx dbo information...

SQL中的迴圈 for迴圈 游標

sql中的迴圈 for迴圈 游標 1.利用游標迴圈更新 刪除memberaccount表中的資料 declare my cursor cursor 定義游標 for select from dbo.memberaccount 查出需要的集合放到游標中 open my cursor 開啟游標 fetc...

SQL中游標的使用

declare studentnum varchar 9 course varchar 10 achievement tinyint,classorder tinyint declare pstudentnum varchar 9 allcourse varchar 60 declare allac...