合并字段是拆分字段处理的逆过程,下面将针对实例进行分析求解。
问题:将具有相同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以
下版本中使用。