我目前正在尝试为传递到存储过程的xml变量选择多个节点。但我只从它的xml中获得一个节点。如何列出所有项目名称和字符串值?
测试代码:
DECLARE @T TABLE (AllXml ntext)
INSERT @T VALUES('<error>
<item name="item 1">
<value string="string 1" />
</item>
<item name="item 2">
<value string="string 2" />
</item>
<item name="item 3">
<value string="string 3" />
</item>
</error>')
SELECT
CAST(AllXml as xml).value('(/error/item/@name)[1]', 'varchar(100)' ),
CAST(AllXml as xml).value('(/error/item/value/@string)[1]', 'varchar(max)' )
FROM @T
期望的结果:
Item 1 string 1
Item 2 string 2
Item 3 string 3
答案 0 :(得分:1)
您可以使用CROSS Apply来实现它。并Sub-Select
。
SELECT
m.c.value('(@name)[1]', 'varchar(100)') AS Name,
m.c.value('(value/@string)[1]', 'varchar(max)') AS Value
FROM
(
SELECT CAST(AllXml as xml) AllXml
FROM @T
) AS data
CROSS APPLY AllXml.nodes('/error/item') as m(c)
或者你可以再使用CROSS APPLY
,如下所示
SELECT
m.c.value('(@name)[1]', 'varchar(100)') AS Name,
m.c.value('(value/@string)[1]', 'varchar(max)') AS Value
FROM @T
CROSS APPLY (SELECT CAST(AllXml AS XML)) as D(D)
CROSS APPLY D.D.nodes('/error/item') as m(c)