国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

深入SQL Cursor基本用法的詳細介紹

2024-08-31 00:57:28
字體:
來源:轉載
供稿:網友
由于這個游標 執行一下就相當于SELECT一下 其效率不敢恭維也沒做深入研究。

復制代碼 代碼如下:


table1結構如下
id int
name varchar(50)

declare @id int
declare @name varchar(50)
declare cursor1 cursor for--定義游標cursor1
select * from table1--使用游標的對象(跟據需要填入select文)
open cursor1--打開游標

fetch next from cursor1 into @id,@name --將游標向下移1行,獲取的數據放入之前定義的變量@id,@name中

while @@fetch_status=0--判斷是否成功獲取數據
begin
update table1 set name=name+'1'
where id=@id--進行相應處理(跟據需要填入SQL文)

fetch next from cursor1 into @id,@name --將游標向下移1行
end

close cursor1--關閉游標
deallocate cursor1


游標一般格式:
DECLARE 游標名稱 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
OPEN 游標名稱
FETCH NEXT FROM 游標名稱 INTO 變量名1,變量名2,變量名3,...
WHILE @@FETCH_STATUS=0
BEGIN
SQL語句執行過程... ...
FETCH NEXT FROM 游標名稱 INTO 變量名1,變量名2,變量名3,...
END
CLOSE 游標名稱
DEALLOCATE 游標名稱 (刪除游標)

復制代碼 代碼如下:


例子:
/*
功能:數據庫表格tbl_users數據
deptid userid username
1100a
1101b
2102c
要求用一個sql語句輸出下面結果
deptid username
1ab
2c
[要求用游標實現設計: OK_008
時間: 2006-05
備注:無
*/
create table #Temp1(deptid int,userid int,username varchar(20)) --待測試的數據表
create table #Temp2(deptid int,username varchar(20))--結果表
--先把一些待測試的數據插入到待測試表#Temp1中
insert into #Temp1
select 1,100,'a' union all
select 1,101,'b' union all
select 1,131,'d' union all
select 1,201,'f' union all
select 2,302,'c' union all
select 2,202,'a' union all
select 2,221,'e' union all
select 3,102,'y' union all
select 3,302,'e' union all
select 3,121,'t'
--
declare @deptid int,@username varchar(20)
--定義游標
declare Select_cursor cursor for
select deptid,username from #Temp1
open Select_cursor
fetch next from Select_cursor into @deptid,@username --提取操作的列數據放到局部變量中
while @@fetch_status=0--返回被 FETCH 語句執行的最后游標的狀態
/*
@@FETCH_STATUS =0FETCH 語句成功
@@FETCH_STATUS =-1 FETCH 語句失敗或此行不在結果集中
@@FETCH_STATUS =-2 被提取的行不存在
*/
begin
--當表#Temp2列deptid存在相同的數據時,就直接在列username上追加@username值
if(exists(select * from #Temp2 where deptid=@deptid ))
update #Temp2 set username=username +@username where deptid=@deptid
else
--插入新數據
insert into #Temp2 select @deptid,@username
fetch next from Select_cursor into @deptid,@username
end
close Select_cursor
deallocate Select_cursor
select * from #Temp2 --測試結果
Drop table #Temp1,#Temp2

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金溪县| 高要市| 韶关市| 敦化市| 安达市| 翁牛特旗| 宝坻区| 保亭| 辉县市| 封开县| 邵阳县| 合江县| 九寨沟县| 天峻县| 西安市| 天等县| 香港 | 天等县| 汶上县| 皮山县| 那曲县| 卢氏县| 留坝县| 嵊州市| 田阳县| 永年县| 孟州市| 华阴市| 梓潼县| 靖边县| 西宁市| 龙胜| 滁州市| 仙游县| 双城市| 泌阳县| 西林县| 云林县| 开原市| 玉山县| 永丰县|