SQL游標的使用

2022-02-13 00:30:29 字數 2826 閱讀 1811

sql游標的使用

2008-09-29 13:57

一、游標包括兩個部分:

1、游標結果集      由定義該游標的select語句返回的行的集合

2、游標位置         指向這個集合中某行的指標

二、游標處理過程:

使用declare 語句宣告

使用open語句開啟

使用fecth語句從游標中提取資料

判斷是否為空,為空no則返回上一步,不為空yes

使用close關閉

使用deallocate釋放

1、宣告游標:

declare 游標名 [insensitive] [scroll] cursor for select語句     [for ]

說明: insensitive 定義乙個游標,以建立將由該游標使用的資料的臨時複本。

scroll指定所有的提取項(first,last,prior,next,relative,absolute)均可用,預設為next

在select語句中不允許用compute,compute by ,for browse和into

2、開啟游標:

open | 游標變數

說明:global 為全域性游標

3、從開啟的游標中提取行

三、游標型別

const adopenforwardonly = 0

前向游標,為預設游標,提供最快的執行效能。用它開啟recordset,從對至尾順序取得所有結果。它不支援向後滾動,只允許在結果間單向移動。

const adopenkeyset = 1

靜態游標,反映第一次開啟游標時表中資料的狀態,游標無法查明底層表中的資料行是否更新過、刪除過或新增了新的資料。不過與只能前移的洲標不同,靜態游標可以在結果間前後滾動。

const adopendynamic = 2

鍵盤驅動的游標,可以查詢表中底層資料行的某些變化,但不是全部。它特別是可以準確反映資料是否更新過。但它不能查明其它使用者是否曾刪除過資料行(刪除掉的資料行在recordset中會留下空洞)。鍵盤驅動的游標支援在結果間前後滾動。

const adopenstatic = 3

動態游標,是最豐富的游標型別。游標開啟時可以查詢其他使用者對錶的任何改動,而且支援滾動。

加鎖型別

const adlockreadonly = 1

預設的上鎖型別,唯讀方式上鎖允許多個使用者同時讀取同樣的資料,但不能改變資料。

const adlockpessimistic = 2

以悲觀上鎖方式開啟資料物件。該方式假定在你編輯記錄時會有其它使用者訪問資料。此時一旦你開始編輯記錄,其它使用者就不能訪問該資料。

const adlockoptimistic = 3

以樂觀上鎖方式開啟資料物件。該方式假定在你編輯記錄時不會有其它使用者訪問資料。在完成改變之前,其它使用者不能訪問該記錄。

const adlockbatchoptimistic = 4

執行多行批處理更新時使用這種型別

六、綜合例項

用sql server游標語句列印報表

declare authors_cursor cursor for

select au_id, au_fname, au_lname

from authors

where state = "ut"

order by au_id

open authors_cursor

fetch next from authors_cursor

into @au_id, @au_fname, @au_lname

while @@fetch_status = 0

begin

print " "

select @message = "----- books by author: " +

@au_fname + " " + @au_lname

print @message

-- declare an inner cursor based

-- on au_id from the outer cursor.

declare titles_cursor cursor for

select t.title

from titleauthor ta, titles t

where ta.title_id = t.title_id and

ta.au_id = @au_id -- variable value from the outer cursor

open titles_cursor

fetch next from titles_cursor into @title

if @@fetch_status <> 0

print " <>"

while @@fetch_status = 0

begin

select @message = " " + @title

print @message

fetch next from titles_cursor into @title

end

close titles_cursor

deallocate titles_cursor

-- get the next author.

fetch next from authors_cursor

into @au_id, @au_fname, @au_lname

end

close authors_cursor

deallocate authors_cursor

go

SQL 游標的使用

我們都知道在關聯式資料庫中,都是面向集合進行查詢的,而游標卻是化整為零,是按行查詢的,舉個例子比如說之前那個壕買了99臺蘋果6,他可以一次性就買了99臺,這正是我們平常使用sql的方式,他也可以分成若干次買,這就是游標的方式,一次只查詢一行。游標分為游標型別和游標變數,對於游標變數來說,游標變數支援...

SQL游標的使用

table1結構如下 id int name varchar 50 declare id int declare name varchar 50 declare cursor1 cursor for 定義游標cursor1 select from table1 使用游標的物件 跟據需要填入selec...

SQL迴圈游標的使用

今天搞的,幫同事查詢資料,先寫個觸發器,擷取http www.chinaroyalgroup.cn aspnet client system web 2 0 50727 dispbbs.asp?boardid 1 id 836裡的網域名稱 if exists select name from sys...