我正在编写一个存储过程,我必须从db创建一个xml列。
µ = CHAR(181)
这是值分隔符,
¶ = CHAR(182)
这是行分隔符
这是我写的声明。我知道它不是很好。
SELECT @xmlString= CAST('<root><Section> ID =' + REPLACE(REPLACE ('20211µ1¶20212µ2', CHAR(182),
'</Section><Section> ID ='),CHAR(181), ' Slno=') + '</Section></root>' AS XML)
这是我需要这样显示的模式。
<root>
<sections id="20211" slno="1" ></sections>
<sections id="20215" slno="2" ></sections>
</root>
答案 0 :(得分:1)
declare @s varchar(50) = '20211µ1¶20212µ2'
declare @xmlString xml
;with C as
(
select T.N.value('value[1]', 'int') as id,
T.N.value('value[2]', 'int') as slno
from (select cast('<item><value>'+replace(replace(@s, 'µ','</value><value>'), '¶','</value></item><item><value>')+'</value></item>' as xml)) as X(XMLCol)
cross apply X.XMLCol.nodes('item') as T(N)
)
select @xmlString =
(
select C.id as [@id] ,
C.slno as [@slno]
from C
for xml path('sections'), root('root'), type
)
select @xmlString
结果:
<root>
<sections id="20211" slno="1" />
<sections id="20212" slno="2" />
</root>