您的位置:首页 > 数据库

SQL Server2005 拆分-去重-合并

2014-02-27 15:03 134 查看
--测试表
if OBJECT_ID('test') is not null
drop table test
go
create table test
(

[key] varchar(20)
)
go
insert test
select 'a,b' union all
select 'b,c'
select * from test

/*
key
--------------------
a,b
b,c

(2 行受影响)
*/
--拆分去重
select
distinct
SUBSTRING([key],number,CHARINDEX(',',[key]+',',number)-number) as [key]
into #a
from
test a,master..spt_values
where
number >=1 and number<=len([key])
and [type]='p'
and substring(','+[key],number,1)=','
select * from #a
/*
key
--------------------
a
b
c

(3 行受影响)
*/
--合并
SELECT distinct
stuff((SELECT ','+[key] FROM #a
FOR XML PATH('')
),1,1,'') AS [key]
FROM #a a

/*
key
---------------------
a,b,c

(1 行受影响)
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SQL Server 合并 拆分