尝试解析多个 xml 文件。 但在应用交叉应用时堆栈
第一个变体工作正常
DECLARE @input XML =
'<a>
<b>
<g>one</g>
<n>
<c>somedata1 1</c>
</n>
<n>
<c>2somedata 2</c>
</n>
</b>
</a>'
SELECT
g = XC.value('(g)[1]', 'varchar(100)'),
i = xc1.n1.value ('(c)[1]', 'varchar(100)')
FROM @input.nodes ('a/b') as XT (XC)
cross apply @input.nodes ('//n') as xc1(n1)
第二个变体失败(返回空字段) - 我知道这是因为缺少 <с> 节点
DECLARE @input XML =
'<a>
<b>
<g>one</g>
</b>
</a>'
SELECT
g = XC.value('(g)[1]', 'varchar(100)'),
i = xc1.n1.value ('(c)[1]', 'varchar(100)')
FROM @input.nodes ('a/b') as XT (XC)
cross apply @input.nodes ('//n') as xc1(n1)
我处理多个文件,其中一些有这些节点,有些没有,我的决定应该是什么?
最佳答案
在第二种情况下,您没有任何 n
元素。您需要使用OUTER APPLY
:
There are two forms of APPLY: CROSS APPLY and OUTER APPLY. CROSS APPLY returns only rows from the outer table that produce a result set from the table-valued function. OUTER APPLY returns both rows that produce a result set, and rows that do not, with NULL values in the columns produced by the table-valued function.
DECLARE @input XML =
'<a>
<b>
<g>one</g>
</b>
</a>';
SELECT g = XC.value('(g)[1]', 'varchar(100)'),
i = xc1.n1.value ('(c)[1]', 'varchar(100)')
FROM @input.nodes ('a/b') AS XT (XC)
OUTER APPLY @input.nodes ('//n') AS xc1(n1);
输出:
╔═════╦══════╗
║ g ║ i ║
╠═════╬══════╣
║ one ║ NULL ║
╚═════╩══════╝
关于sql - 解析xml时如何使用 "cross apply"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36446947/