加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver实现取相同名称放在同一字段

发布时间:2020-12-12 15:49:57 所属栏目:MsSql教程 来源:网络整理
导读:? if object_id('[tbtest]') is not null drop table [tbtest] ? create table tbtest ? ( ??? A varchar(10) not null, ??? B varchar(50) not null ? ) ? go ? insert into tbtest ? select 'A',1 union all ? select'A',2 union all ? select'A',3 union

? if object_id('[tbtest]') is not null drop table [tbtest]
? create table tbtest
? (
??? A varchar(10) not null,
??? B varchar(50) not null
? )
? go
? insert into tbtest
? select 'A',1 union all
? select'A',2 union all
? select'A',3 union all
? select'B',4 union all
? select'B',5 union all
? select'B',6 union all
? select'B',7 union all
? select'C',8 union all
? select'C',9 union all
? select'C',10 union all
? select'C',11
?
? go

? if object_id('[dbo].[functiontest]') is not null drop function [dbo].[functiontest]
? go

? create??? function?? functiontest()??
? returns?? @tb?? table(A?? varchar(10),B?? varchar(50))??
? AS
? begin?
? declare @a varchar(50)
? declare @b varchar(50)
? declare temp_cur cursor local for
? select * from tbtest
? open temp_cur
? fetch next from temp_cur into @a,@b
? while (@@fetch_status = 0)
? begin
?? if(not exists(select * from @tb where A = @a))
????? insert into @tb(A,B)values(@a,@b)
?? else
??? update @tb set B = B + ',' + @b where A = @a
?? fetch next from temp_cur into @a,@b
? end
? return??
? end??
? go

? select * from functiontest()?? ? go

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读