資料庫作業17 SQL練習9 CURSOR

2021-10-06 23:01:16 字數 1270 閱讀 1641

使用游標的原因:

sql語言是面向集合的,一條sql語句原則上可以產生或處理多條記錄

主語言是面向記錄的,主變數一次只能存放一條記錄使用主變數並不能完全滿足sql語句向應用程式輸出資料的要求,嵌入式sql引入了游標的概念,用來協調這兩種不同的處理方式

游標是系統為使用者開設的資料緩衝區,存放sql語句的執行結果

每個游標區都有乙個名字,使用者可以用sql語句逐一從游標中獲取記錄,並賦給主變數,交由主語言進一步處理

我覺得游標就是乙個標記,它在資料中記錄我們讀取資料或寫入資料進行到了**,可在標記位置繼續操作。

if (exists (select * from sys.objects where name = 『proc_cursor』))

drop procedure proc_cursor

gocreate procedure proc_cursor --建立儲存過程 名為proc_cursor

asdeclare @sno char(9)–定義變數

declare @sname char(20)–定義變數

declare mycursor cursor for select sno,sname from student --宣告游標 名為mycursor用到student表

open mycursor --開啟游標

fetch next from mycursor into @sno,@sname

while(@@fetch_status=0) --遍歷所有的資料

begin

print @sno

print @sname

fetch next from mycursor into @sno,@sname --取下一條游標資料

endclose mycursor --關閉游標

deallocate mycursor --刪除游標

goexec proc_cursor --exec執行

go

執行結果:

201215126

張成民游標:用來協調主語言和sql對於輸出資料的不協調。

是系統為使用者開設的資料緩衝區,存放sql的處理結果

游標宣告

declare 《游標名》 cursor for 《查詢語句》;

開啟游標

open 游標名

關閉游標

close 游標名

刪除游標

deallocate 游標名

取出資料

fetch from 游標名 into 變數

資料庫作業17 SQL練習9 CURSOR

if exists select from sys.objects where name proc cursor drop procedure proc cursor gocreate procedure proc cursor 建立儲存過程 procedure 名為proc cursor as d...

資料庫作業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 內逐行地訪問這些記錄,按照使用者自己的意願來顯示和處理這些記錄...