简体   繁体   English

sql如何在正确解析xml中应用“交叉应用”

[英]sql how to aplly "cross apply" in parsing xml correctly

Trying to parse multiple xml files.试图解析多个 xml 文件。 But stack in applying cross apply但是堆栈在应用交叉应用

First variant works fine第一个变体工作正常

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)

second variant fails (returns empty fields) - I know this is becouse absence of <с> nodes第二个变体失败(返回空字段) - 我知道这是因为没有 <с> 节点

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)

I working with multiple files, and some of them have those nodes and some no, what is my decision supposed to be?我处理多个文件,其中一些有这些节点,有些没有,我的决定应该是什么?

In second case you don't have any n element.在第二种情况下,您没有任何n元素。 You need to use OUTER APPLY :您需要使用OUTER APPLY

There are two forms of APPLY: CROSS APPLY and OUTER APPLY. APPLY有两种形式:CROSS APPLY和OUTER APPLY。 CROSS APPLY returns only rows from the outer table that produce a result set from the table-valued function. CROSS APPLY 仅返回从表值函数生成结果集的外部表中的行。 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. OUTER APPLY 返回生成结果集的行和不生成结果集的行,在表值函数生成的列中具有 NULL 值。

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);

LiveDemo

Output:输出:

╔═════╦══════╗
║  g  ║  i   ║
╠═════╬══════╣
║ one ║ NULL ║
╚═════╩══════╝

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM