首先是Sql server下的用法:
一个表结构如下: id name contetID
1 test 1
2 test1 1
3 test2 1
4 test3 2
5 test4 2
把它的记录加入另一个表中,结构如下:
contetID names
1 test,test1,test2
2 test3,test4
if OBJECT_ID('A','U')is not null drop table A
go
create table A
(
id int, name nvarchar(10), contetID int
)
go
insert into A
select 1, 'test', 1 union all
select 2, 'test1', 1 union all
select 3, 'test2', 1 union all
select 4, 'test3', 2 union all
select 5, 'test4', 2
go
select distinct contetID,
name=stuff((select ','+name from A as b where a.contetID=b.contetID for XML path('')),1,1,'')
from A as a
/*
contetID name
----------- ----------------
1 test,test1,test2
2 test3,test4
*/
--将上面的结果直接插入另一张表中即可
insert into othertb
select distinct contetID,
name=stuff((select ','+name from A as b where a.contetID=b.contetID for XML path('')),1,1,'')
from A as a
go
create table A
(
id int, name nvarchar(10), contetID int
)
go
insert into A
select 1, 'test', 1 union all
select 2, 'test1', 1 union all
select 3, 'test2', 1 union all
select 4, 'test3', 2 union all
select 5, 'test4', 2
go
select distinct contetID,
name=stuff((select ','+name from A as b where a.contetID=b.contetID for XML path('')),1,1,'')
from A as a
/*
contetID name
----------- ----------------
1 test,test1,test2
2 test3,test4
*/
--将上面的结果直接插入另一张表中即可
insert into othertb
select distinct contetID,
name=stuff((select ','+name from A as b where a.contetID=b.contetID for XML path('')),1,1,'')
from A as a
核心函数:
1. select ','+name for XML path('') :产生,test,test1,test2。 for XML path本来是用来生产xml格式数据的,详情见下:
http://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.html
2. stuff :
Stuff(expression1_Str,startIndex,lengthInt,expression2_Str)函数共有四个参数,其功能是将expression1_Str中自startIndex位置起删除lengthInt个字符,然后将expression2插入到expression1_Str中的startIndex位置。
在此处用于去除xml path产生的字串中第一个,号。
然后,在Oracle中,没有for xml path,但是提供了更方便的函数:
函数wm_concat(列名),该函数可以把列值以","号分隔起来,并显示成一行
http://blog.itpub.net/post/42245/522757
http://www.ningoo.net/html/2008/how_to_do_string_aggregate_on_oracle.html