Sqlserver 游標簡單示例

2022-07-26 07:39:11 字數 1439 閱讀 5613

--建立乙個游標

declare my_cursor cursor for --my_cursor為游標的名稱,隨便起

select id,name from my_user --這是游標my_cursor的值,這裡隨便發揮看業務場景

--開啟游標

open my_cursor --沒什麼好說的

--變數

declare @id int --宣告變數 『declare』為宣告變數 『@name』為變數名稱 後面為變數型別

declare @name varchar(50) --這裡是兩個變數用來接收游標的值

--迴圈游標

fetch next from my_cursor into @id,@name --獲取my_cursor的下一條資料,其中為兩個字段分別賦值給@id,@name

while @@fetch_status=0 --假如檢索到了資料繼續執行

begin

print(@name) --print()列印變數 隨便發揮

select * from my_user where id=@id --這裡是具體業務了,隨便發揮。而我這是又執行了一次查詢 

fetch next from my_cursor into @id,@name --獲取下一條資料並賦值給變數

end--關閉釋放游標

close my_cursor

deallocate my_cursor

--建立乙個游標

declare my_cursor cursor for --my_cursor為游標的名稱,隨便起

select id,name from my_user --這是游標my_cursor的值,這裡隨便發揮看業務場景

--開啟游標

open my_cursor --沒什麼好說的

--變數

declare @id int --宣告變數 『declare』為宣告變數 『@name』為變數名稱 後面為變數型別

declare @name varchar(50) --這裡是兩個變數用來接收游標的值

--迴圈游標

fetch next from my_cursor into @id,@name --獲取my_cursor的下一條資料,其中為兩個字段分別賦值給@id,@name

while @@fetch_status=0 --假如檢索到了資料繼續執行

begin

print(@name) --print()列印變數 隨便發揮

select * from my_user where id=@id --這裡是具體業務了,隨便發揮。而我這是又執行了一次查詢 

fetch next from my_cursor into @id,@name --獲取下一條資料並賦值給變數

end--關閉釋放游標

close my_cursor

deallocate my_cursor

SQL Server 游標示例

建立測試臨時表 if object id tempdb.books is not null begin drop table books endcreate table books bookname nvarchar 20 bookcode nvarchar 20 insert into books...

sqlserver簡單游標使用

這個是乙個簡單的user表叫my user 以下 及注釋 注 為注釋 建立乙個游標 declare my cursor cursor for my cursor為游標的名稱,隨便起 select id,name from my user 這是游標my cursor的值,這裡隨便發揮看業務場景 開啟游...

sqlserver游標的簡單例子

游標是sql 的一種資料訪問機制。可以將游標簡單的看成是查詢的結果集的乙個指標。可以根據需要在結果集上面來回滾動,瀏覽儲存需要的資料,以便以後使用。游標的結果集是有select語句產生,如果處理過程需要重複使用乙個記錄集,那麼建立一次游標而重複使用,比重複查詢資料庫要快。游標的使用一般遵循 五步法 ...