MS SQL 字符拆分与合并
--Excel导入数据
if OBJECT_ID('tbl_test') is not null drop table tbl_test
SELECT *
into tbl_test
FROM OpenDataSource
( 'Microsoft.ACE.OLEDB.12.0',
'Data Source=C:\Work\eCat\LevelBasedApplication\test.xlsx;
User ID=Admin;Password=;Extended properties=Excel 12.0')...[Sheet1$]
select * from tbl_test
数据长这样
key value
test1 a,b,ccd,e
test2 a,aa,bb,c
test3 a,aa,b,bb
--拆开
if OBJECT_ID('tbl_test_combine') is not null drop table tbl_test_combine
select distinct a.[key],value = substring(a.value , b.number , charindex(';' , a.[value] + ';' , b.number) - b.number)
into tbl_test_combine
from tbl_test a join master..spt_values b
on b.type='p' and b.number between 1 and len(a.[value])
where substring(';' + a.value , b.number , 1) = ';'
结果:
key value
test1 a
test1 b
test1 ccd
test1 e
test2 a
test2 aa
test2 bb
test2 c
test3 a
test3 aa
test3 b
test3 bb
--合并
SELECT
[key]
,'value' = (
STUFF(
(SELECT ','+value
FROM tbl_test_combine
WHERE [key] = A.[key]
FOR xml path('')
),1,1,''
)
)
FROM tbl_test_combine A
--where [FAS KEY] ='OUG0000043'
GROUP by [key]
结果:
key value
test1 a,b,ccd,e
test2 a,aa,bb,c
test3 a,aa,b,bb