MS SQL游標的使用及理解

2021-04-12 18:30:00 字數 2404 閱讀 6251

與windows或dos的「游標」不同,ms-sql的游標是一種臨時的資料庫物件,既對可用來旋轉儲存在系統永久表中的資料行的副本,也可以指向儲存在系統永久表中的資料行的指標。

游標為您提供了在逐行的基礎上而不是一次處理整個結果集為基礎的操作表中資料的方法。

1.如何使用游標

1)定義游標語句 declare 《游標名》 cursor  for

2)建立游標語句 open 《游標名》

3)提取游標列值、移動記錄指標 fetch  《列名列表》  from  《游標名》  [into 《變數列表》]

4)使用@@fetch_status利用while迴圈處理游標中的行

5)刪除游標並釋放語句 close  《游標名》/deallocate  《游標名》

6)游標應用例項

--定義游標

declare cur_depart cursor

for  select  cdeptid,cdeptname  from  department  into  @deptid,@deptname

--建立游標

open cur_depart

--移動或提取列值

fetch  from  cur_depart  into  @deptid,@deptname

--利用迴圈處理游標中的列值

while  @@fetch_status=0

begin

print @deptid,@deptname

fetch  from  cur_depart into  @deptid,@deptname

end--關閉/釋放游標

close  cur_depart

deallocate  cur_depart

2.語句的詳細及注意

1)定義游標語句

declare 《游標名》  [insensitive] [scroll]  cursor

for2)提取游標列值、移動記錄指標語句

fetch  [next | prior | first | last | | ]

from  《游標名》  [into 《變數列表……>]

3)基於游標的定位delete/update語句

如果游標是可更新的(也就是說,在定義游標語句中不包括read only 引數),就可以用游標從游標資料的源表中delete/update行,即delete/update基於游標指標的當前位置的操作;

舉例:--刪除當前行的記錄

declare cur_depart cursor

for  select  cdeptid,cdeptname  from  department  into  @deptid,@deptname

open cur_depart

fetch  from  cur_depart  into  @deptid,@deptname

delete  from  department  where  current  of  cur_depart

--更新當前行的內容

declare cur_depart cursor

for  select  cdeptid,cdeptname  from  department  into  @deptid,@deptname

open cur_depart

fetch  from  cur_depart  into  @deptid,@deptname

update  department  set  cdeptid=』2007』 + @deptid  where  current  of  cur_depart

3.游標使用技巧及注意

1)利用order by改變游標中行的順序。此處應該注意的是,只有在查詢的中select 子句中出現的列才能作為order by子句列,這一點與普通的select語句不同;

2)當語句中使用了order by子句後,將不能用游標來執行定位delete/update語句;如何解決這個問題,首先在原表上建立索引,在建立游標時指定使用此索引來實現;例如:

declare cur_depart cursor

for  select  cdeptid,cdeptname  from  department  with  index(idx_id)

for  update  of  cdeptid,cdeptname

通過在from子句中增加with index來實現利用索引對錶的排序;

3)在游標中可以包含計算好的值作為列;

4)利用@@cursor_rows確定游標中的行數;

MS SQL游標的使用及理解

與windows或dos的 游標 不同,ms sql的游標是一種臨時的資料庫物件,既對可用來旋轉儲存在系統永久表中的資料行的副本,也可以指向儲存在系統永久表中的資料行的指標。游標為您提供了在逐行的基礎上而不是一次處理整個結果集為基礎的操作表中資料的方法。1 如何使用游標 1 定義游標語句 decla...

MSSQL 游標的使用

與windows或dos的 游標 不同,ms sql的游標是一種臨時的資料庫物件,既對可用來旋轉儲存在系統永久表中的資料行的副本,也可以指向儲存在系統永久表中的資料行的指標。游標為您提供了在逐行的基礎上而不是一次處理整個結果集為基礎的操作表中資料的方法。1 如何使用游標 1 定義游標語句 decla...

MSSQL 游標的建立和使用

一 顯示效果 1 執行指令碼 declare username varchar 32 定義變數username declare password varchar 32 定義變數password fetch mycursor into id username,password while fetch ...