資料庫作業17 SQL練習9 CURSOR

2021-10-05 08:28:09 字數 2255 閱讀 5810

if

(exists

(select

*from sys.objects where name =

'proc_cursor'))

drop

procedure proc_cursor

gocreate

procedure proc_cursor --建立儲存過程(procedure)名為proc_cursor

as--declare宣告

declare

@sno

char(9

)--定義變數

declare

@sname

char(20

)--定義變數

declare mycursor cursor

forselect sno,sname from student --宣告游標(cursor)名為mycursor;用到student表

open mycursor --開啟游標

fetch

next

from mycursor into

@sno

,@sname

--fetch取值

while

(@@fetch_status=0

)--遍歷所有的資料 fetch_status取狀態

begin

print

'游標成功取出一條資料:'

print

@sno

print

@sname

print

'********************'

fetch

next

from mycursor into

@sno

,@sname

--取下一條游標資料

endclose mycursor --關閉游標

deallocate mycursor --刪除游標go

exec proc_cursor --exec執行

go

執行:

游標的使用

if

(exists

(select

*from sys.objects where name =

'過程名'))

drop

procedure 過程名

go --若刪除,則:'create/alter procedure' 必須是查詢批次中的第乙個語句。

create

procedure 過程名 --建立儲存過程(procedure)

as--declare宣告變數、游標(cursor):

declare @變數名 char(9

)--定義變數

declare 游標名 cursor

forselect..

.from..

.--宣告游標

open 游標名 --開啟游標

fetch

next

from 游標名 into @變數名,@變數名,..

.--fetch取值,變數取對應(select)游標值

while

(@@fetch_status=0

)--遍歷所有的資料 fetch_status取狀態

begin

--print輸出

print @變數名 --輸出變數

print

'******'

--輸出字串

fetch

next

from 游標名 into @變數名,@變數名,..

.--取下一條游標資料

endclose 游標名 --關閉游標

deallocate 游標名 --刪除游標go

exec 過程名 --exec執行

go

declare 游標名 cursor

forselect..

.from..

.--宣告游標

open 游標名 --開啟游標

fetch

next

from 游標名 into @變數名,@變數名,..

.--變數取游標值

close 游標名 --關閉游標

deallocate 游標名 --刪除游標

go

資料庫作業17 SQL練習9 CURSOR

if exists select from sys.objects where name proc cursor drop procedure proc cursor 如果存在,就刪除過程 gocreate procedure proc cursor 儲存過程 asdeclare sno char ...

資料庫作業17 SQL練習9 CURSOR

為何使用游標 使用游標 cursor 的乙個主要的原因就是把集合操作轉換成單個記錄處理方式。用 sql 語言從資料庫中檢索資料後,結果放在記憶體的一塊區域中,且結果往往是乙個含有多個記錄的集合。游標機制允許使用者在 sql server 內逐行地訪問這些記錄,按照使用者自己的意願來顯示和處理這些記錄...

資料庫作業17 SQL練習9 CURSOR

將sql嵌入到高階語言中混合程式設計,程式中會含有兩種不同計算模型的語句 1 sql語句 描述性的面向集合的語句,負責操縱資料庫 2 高階語言語句 c語言 過程性的面向記錄的語句,負責控制邏輯流程 c 中可以使用datatable讀取記錄,進一步逐條讀取記錄 什麼是游標?游標是系統為使用者開設的資料...