DECLARE @xml VARCHAR(MAX)='磨毛:1 缩率:2 干磨:3 湿摩:4 水洗牢度:5 手感:6 防水:7 PH:8 日晒:9' SET @xml= '<root>'+CHAR(10)+'<r><v>'+REPLACE(REPLACE(@xml,CHAR(10),'</v1></r>'+CHAR(13)+'<r><v>'),':','</v><v1>')+'</v1></r>'+CHAR(10)+'</root>' BEGIN TRY DECLARE @xml2 XML= @xml SELECT * FROM( SELECT t.v.query('.').value('/r[1]/v[1]','varchar(50)') as gy, t.v.query('.').value('/r[1]/v1[1]','varchar(50)') as gyyq FROM @xml2.nodes('/root/r')t(v)) a PIVOT(MAX(gyyq) FOR gy IN ([磨毛],[缩率],[干磨],[湿摩],[水洗牢度],[手感],[防水],[PH],[日晒])) AS pvt END TRY BEGIN CATCH IF @@ERROR>0 SELECT NULL AS [磨毛],NULL AS [缩率],NULL AS [干磨],NULL AS [湿摩],NULL AS [水洗牢度],NULL AS [手感],NULL AS [防水],NULL AS [PH],NULL AS [日晒] ,ERROR_MESSAGE() END CATCH
--这里展示的是多列的情况
1 CREATE FUNCTION dbo.fn_GetSplitData(@Data NVARCHAR(MAX),@SplitChar VARCHAR(50)) 2 RETURNS TABLE 3 AS 4 RETURN 5 ( 6 with roy as 7 (select COl2=cast(left(@Data,charindex(@SplitChar,@Data+@SplitChar)-1) as VARCHAR(max)),Split=cast(stuff(@Data+@SplitChar,1,charindex(@SplitChar,@Data+@SplitChar),'') as VARCHAR(MAX)) 8 union all 9 select COl2=cast(left(Split,charindex(@SplitChar,Split)-1) as VARCHAR(max)),Split= cast(stuff(Split,1,charindex(@SplitChar,Split),'') as VARCHAR(max)) 10 FROM Roy where split>'' 11 ) 12 select COl2 AS Col from roy 13 14 15 /*SELECT b.Col */ 16 /*FROM */ 17 /*(SELECT convert(xml,'<root><v>'+replace(@Data,@SplitChar,'</v><v>')+'</v></root>') AS Col)a */ 18 /*CROSS apply(SELECT Col=C.v.value('.','nvarchar(100)') from a.Col.nodes('/root/v')C(v))b */ 19 ) 20 GO