篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql MS SQL特定格式到XML相关的知识,希望对你有一定的参考价值。
-------------------------------------------------------------
-- [ DATA FORMAT 3 ]
-------------------------------------------------------------
-- 'A#B#C,p#q#r,a#b#c,l#m#n,rs#tt#g';
--- MID FORMAT:
-- <Y>
-- <X>A</X>
-- <X>B</X>
-- <X>C</X>
-- </Y>
-- <Y>
-- <X>p</X>
-- <X>q</X>
-- <X>r</X>
-- </Y>
-- <Y>
-- <X>a</X>
-- <X>b</X>
-- <X>c</X>
-- </Y>
-------------------------------------------------------------
-- [ CODE ]
DECLARE @xml AS XML ,
@str AS VARCHAR(200) = 'A#B#C,p#q#r,a#b#c,l#m#n,rs#tt#g' ,
@comma AS VARCHAR(10) = ',' ,
@hash AS VARCHAR(10) = '#';
SET @str = ( REPLACE(@str, @hash, '</X><X>') );
SET @str = '<Y><X>' +
( REPLACE(@str, @comma, '</X></Y><Y><X>') ) +
'</X></Y>';
PRINT @str;
SET @str = ( +REPLACE(@str, @comma, '</Y><Y>') );
SET @xml = CAST(@str AS XML);
SELECT N.value('(X)[1]', 'varchar(10)') AS value ,
N.value('(X)[2]', 'varchar(10)') AS value2 ,
N.value('(X)[3]', 'varchar(10)') AS value3
FROM @xml.nodes('Y') AS T ( N );
-------------------------------------------------------------
-- [ OUTPUT ]
-- value1 | value2 | value3
---------------------------
-- A B C
-- p q r
-- a b c
-- l m n
-- rs tt g