日期:2014-05-17 浏览次数:20576 次
--分解字符
WITH a1 (id,msg) AS
(
SELECT 1,'msg1=a msg2=b msg3=c' UNION ALL
SELECT 2,'msgx=aa msg2=bbb msg1=c msg3=c'
)
,a2 AS
(SELECT id,','+REPLACE(msg,' ',',')+',' cstr FROM a1)
,a3 AS
(
SELECT id,cstr,CHARINDEX(',',cstr,1) n1,1 n2
FROM a2
UNION ALL
SELECT id,cstr,CHARINDEX(',',cstr,n1+1) n1,n2+1
FROM a3
WHERE CHARINDEX(',',cstr,n1+1)>0
)
,a4 AS
(SELECT id,cstr,n1,(SELECT n1 FROM a3 WHERE cstr=a.cstr AND n2=a.n2+1) n2 FROM a3 a)
,a5 AS
(
SELECT id,SUBSTRING(cstr,n1+1,n2-n1-1) cstr FROM a4 WHERE n2 IS NOT NULL
)
SELECT id,LEFT(cstr,CHARINDEX('=',cstr)-1) cstr1,right(cstr,LEN(cstr)-CHARINDEX('=',cstr)) cstr2
INTO #temp
FROM a5
ORDER BY id
--組合動態SQL語句
DECLARE @sql NVARCHAR(MAX), @colList NVARCHAR(MAX)
SET @colList = STUFF(
(
SELECT ','+QUOTENAME(cstr1)
FROM (SELECT DISTINCT cstr1 FROM #temp) t
FOR XML PATH('')
),1,1,'')
SET @sql = N'
select *
from #temp a
pivot
(max(cstr2) for cstr1 in('+ @colList +')) b
'
EXEC(@sql)