遊標一般格式:
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
1 100 a
1 101 b
2 102 c
要求用一個sql語句輸出下面結果
deptid username
1 ab
2 c
[要求用遊標實現設計: 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 =0 FETCH 語句成功
@@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