技术开发 频道

SQL游标学习

  【IT168技术文档】

  功能:数据库表格tbl_users数据

deptid userid username
1 100 a
1 101 b
2 102 c

  要求用一个sql语句输出下面结果[要求用游标实现]
deptid username
1 ab
2 c

create table #Temp1(deptid int,userid int,username varchar(20)) create table #Temp2(deptid int,username varchar(20)) 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 begin 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
0
相关文章