微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

  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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐