遊標分爲客戶端遊標和服務器端遊標。Sql經過遊標能夠對一個結果集進行逐行處理。對於使用服務器端遊標的過程有:聲明、打開、讀取、關閉、釋放。服務器
Declare cursor_name [insensitive][scroll] cursorfetch
For select_statementspa
[for { readonly|update [of column_name[,…n]]}]作用域
Insensitive:使用查詢結果的副本it
如:io
declare xs_cur1 cursorast
for變量
select* from xs服務器端
where stu_major='計算機'擴展
for read only
Declare cursor_name Cursor
[local | global] /*遊標做用域*/
[forward_only | scroll] /*遊標移動方向*/
[static| keyset | dynamic | fast_forward] /*遊標類型*/
[read_only | scroll_locks | optimistic] /*訪問屬性*/
[tupe_warning] /*類型轉換警告信息*/
For select_statement
[for update [of column_name[,…n]] /*可修改的列*/
Static:靜態遊標,只讀
Keyset:鍵集驅動遊標,能夠經過鍵集驅動遊標修改基本表中非關鍵字列的值。
dynamic :動態遊標
fast_forward:只進遊標
declare xs_cur2 cursor
dynamic
for
select* from xs
where stu_major='計算機'
Open {{[global] cursor_name}| cursor_variable_name}
例子:/*定義遊標,而後打開,輸出其行數*/
declare xs_cur3 cursor
local scroll scroll_locks
for
select stu_id,stu_name,stu_total_credit from xs
for update of stu_total_credit
open xs_cur3
select 'the number of rows'=@@cursor_rows
遊標打開後,就可使用fetch語句從中讀取數據。Fetch語句的格式爲:
Fetch
[next|prior|first|last|absolute{n|@nvar}|relative{n|@nvar}]
From {{[global] cursor_name}| cursor_variable_name}
Into @variable_name[,….n]
如:fetch first from xs_cur2
注意:fetch語句執行的狀態保存在全局變量@@Fetch_status中,其值爲0,表示執行成功;爲-1,表示所要讀取的行不在結果集中;爲-2,表示被提取的行已經不在(已被刪除)。
Close {{[global] cursor_name}| cursor_variable_name}
Deallocate {{[global] cursor_name}| cursor_variable_name}