合并字段

合并字段是拆分字段处理的逆过程,下面将针对实例进行分析求解。
问题:将具有相同id号的name字段合并。
原表Table1(id int,name varchar(100))

id    name
-----------
1     'a'
1     'b'
1     'c'
2     'e'
2     'f'


希望得到结果:

id           name
-------------------
1            'a,b,c'
2            'e,f'

一、利用最原始的方法进行求解,即通过逐条循环来实现,当遇到有相同的id号时就连接name字段,否则插入一条新记录,
此方法较笨拙,不推荐此使用此方法,过程如下:
create table Table1(id int,name varchar(100))
insert Table1(id,name)
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 2,'d'
union all select 2,'e'
union all select 3,'f'
union all select 3,'g'

DECLARE @id int,@name varchar(100)
create table #b(id int,name varchar(100))
DECLARE a_cursor CURSOR FOR
SELECT id, name
FROM Table1
ORDER BY id
 
OPEN a_cursor

FETCH NEXT FROM a_cursor
INTO @id,@name

WHILE @@FETCH_STATUS = 0
BEGIN
  if exists(select 1 from #b where id=@id)
    begin
 update #b
 set name=name+','+@name
 where id=@id 
    end
  else
     insert #b(id,name)
     select @id,@name

  FETCH NEXT FROM a_cursor
  INTO @id, @name
end
CLOSE a_cursor
DEALLOCATE a_cursor

select *from #b
drop table #b,Table1


二、利用合并函数。(此方法适用于SQL2000版本以上)
create table Table1(id int,name varchar(100))
insert Table1(id,name)
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 2,'d'
union all select 2,'e'
union all select 3,'f'
union all select 3,'g'

create function dbo.fn_b(@a varchar(10))
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
select @s=@s+name from Table1 where id=@a
return (@s)
end

select A,B=dbo.fn_b(id) from Table1 group by A

drop Table1

解析:此方法使用了函数,语句简洁易懂,较常用,但不能在低于SQL2000版本中使用。

三、使用特定的排序加update语句来实现。此方法在低于SQL2000版本中也可以使用。
declare @id int,@namelist varchar(100)
create table #a(id int,name varchar(100),namelist varchar(100))
create table Table1(id int,name varchar(100))
insert Table1(id,name)
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 2,'d'
union all select 2,'e'
union all select 3,'f'
union all select 3,'g'
insert #a(id,name)
select * from Table1 order by id--此处插入时一定要按id先排序
update #a
set namelist=@namelist,@namelist=(case when id=@id then @namelist+','+name else name end),@id=id from #a

select id,name=max(namelist) from #a group by id
drop table #a
drop table Table1
解析:此方法借助了临时表,使用了修改语句与分组查询,在效率上与复杂度上都比不上第二种方法,但却可以在SQL2000以
下版本中使用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值