Sql Server 游標的使用

2021-10-07 01:20:06 字數 3481 閱讀 8520

二:游標的語句

三:案例

游標是sql server的一種資料訪問機制,它允許使用者訪問單獨的資料行。使用者可以對每一行進行單獨的處理,從而降低系統開銷和潛在的阻隔情況,使用者也可以使用這些資料生成的sql**並立即執行或輸出。

游標是一種處理資料的方法,主要用於儲存過程,觸發器和 t_sql指令碼中,它們使結果集的內容可用於其它t_sql語句。在檢視或處理結果集中向前或向後瀏覽資料的功能。類似與c語言中的指標,它可以指向結果集中的任意位置,當要對結果集進行逐條單獨處理時,必須宣告乙個指向該結果集中的游標變數。

優點:方便使用者對資料庫中的資料逐條進行處理

缺點:在進行大資料處理時,效率低下,占用的記憶體也比較大

宣告乙個游標

declare mycursor cursor

for select top 5 fbookname,fbookcoding from tbookinfo//定義乙個叫mycursor的游標,存放for select 後的資料

開啟乙個游標

open mycursor//即開啟這個資料集

迴圈乙個游標

declare @bookname nvarchar(2000),@bookcoding nvarchar(2000)

fetch next from mycursor into @bookname,@bookcoding//移動游標指向到第一條資料,提取第一條資料存放在變數中

while @@fetch_status =0//如果上一次操作成功則繼續迴圈

begin

print 『name』+@bookname

fetch next from mycursor into @bookname,@bookcoding//繼續提下一行

end關閉游標

close mycursor

釋放資源

deallocate mycursor

1)首先建立一張客戶表(customers),如圖所示:

實現要求:修改消費等級(consumelevel)這個字段,當消費金額(consumeamount)>1000時,等級為高消費,當500<=消費金額(consumeamount)<1000時,等級為中消費,小於500 等級為低消費****

**如下:

--宣告游標

declare cur_customer cursor

forselect id,consumeamount from customers

--開啟游標

open cur_customer

--通過游標獲取資料,id,comsumeamount 取值

declare

@idint

declare

@cacount

intfetch

next

from cur_customer into

@id,

@cacount

--迴圈往下 判斷如果有資料

while

(@@fetch_status=0

)begin

--修改消費等級if(

@cacount

<

500)

update customers set consumelevel=

'低消費'

where id=

@idelseif(

@cacount

<

1000

)update customers set consumelevel=

'中消費'

where id=

@idelse

update customers set consumelevel=

'高消費'

where id=

@idfetch

next

from cur_customer into

@id,

@cacount

end--關閉游標

close cur_customer

--釋放游標

deallocate cur_customer

最終效果如圖所示:

2)首先建立兩張表,一張客戶表(customers),同上,一張統計表(tongji),不插入任何資料

實現要求:做統計報表,統計客戶表中每天的消費總金額,將該查詢結果,一條條的插入到統計表中

**如下:

--宣告游標

declare cur_tongji cursor

forselect

year

(consumetime) 年,

month

(consumetime) 月,

day(consumetime) 日,

sum(consumeamount) 總金額

from customers group

byyear

(consumetime)

,month

(consumetime)

,day

(consumetime)

--開啟游標

open cur_tongji

--瀏覽資料並獲取

declare

@yy nvarchar(50)

declare

@mm nvarchar(50)

declare

@dd nvarchar(50)

declare

@yye

intfetch

next

from cur_tongji into

@yy,

@mm,

@dd,

@yye

while

(@@fetch_status=0

)begin

insert

into tongji values

(@yy

,@mm

,@dd

,@yye

)fetch

next

from cur_tongji into

@yy,

@mm,

@dd,

@yye

end--關閉游標

close cur_tongji

--釋放游標

deallocate cur_tongji

最終效果如圖所示:

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 把游標指向的資料取出來...