XML to SQL 问题 - 如何获取元素的位置

XML to SQL Issue - How to get position of an element(XML to SQL 问题 - 如何获取元素的位置)
本文介绍了XML to SQL 问题 - 如何获取元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图在 sql 中获取 XML 节点元素的位置,但它没有给我正确的结果,@Shungo 建议使用该方法

I am trying to get the position of an element of an XML node in sql , and it is not giving me correct results , the approach was suggested by @Shungo

这是代码:

declare @xmlVar xml ='
<A specVersion="2.09">
  <B id="1" type="Regular">
    <C>
      <D>
        <E actioncode="A" date="06/13/2018 09:20" />
        <E  actioncode="B" date="06/13/2018 09:20" />
      </D>
      <D>
        <E actioncode="C" date="06/13/2018 09:20" />
      </D>
    </C>
  </B>

  <B id="2" type="Regular">
    <C>
      <D>
        <E  actioncode="D" date="06/13/2018 09:20" />
      </D>
    </C>
  </B>
</A>' ;
    WITH Tally(Nmbr) AS
(
    SELECT TOP (SELECT @xmlVar.value(N'count(/A/B/C/D)','int'))
           ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) 
    FROM master..spt_values --just a pre-filled table with many rows
)
SELECT Nmbr
      ,e.value(N'@actioncode[1]','nvarchar(max)') AS Employee
FROM Tally
OUTER APPLY(SELECT @xmlVar.query(N'/A/B/C/D[sql:column("Nmbr")]')) AS A(ds)
OUTER APPLY ds.nodes(N'D/E') AS B(e);

上面的查询给出了错误的结果:

The above query is giving wrong results :

1   A
1   B
1   D
2   C
3   NULL

预期输出:

1  A
1  B
2  C
3  D

任何帮助将不胜感激.谢谢.

Any help would be appreciated . Thanks.

推荐答案

嗯,这和之前的完全不一样了...

Well, this is quite different to the one before...

看起来,您希望将 <D> 节点放在任何位置.这有帮助吗?

As it looks, you want to take <D> nodes whereever they are placed. Does this help?

WITH Tally(Nmbr) AS
(
    SELECT TOP (SELECT @xmlVar.value(N'count(//D)','int'))
           ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) 
    FROM master..spt_values --just a pre-filled table with many rows
)
SELECT Nmbr
      ,e.value(N'@actioncode[1]','nvarchar(max)') AS Employee
FROM Tally
OUTER APPLY(SELECT  @xmlVar.query(N'//D').query(N'/D[sql:column("Nmbr")]')) AS B(ds)
OUTER APPLY ds.nodes(N'D/E') AS C(e);

第一个应用程序将使用深度搜索(使用//D)来获取仅包含这些节点的派生 XML.其余的和以前一样.

The first apply will use the deep search (with //D) to get a derived XML including these nodes only. The rest is rather the same as before.

这篇关于XML to SQL 问题 - 如何获取元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Dynamically group by with quot;Group Headerquot;(使用“组头动态分组)
How to retrieve leaf path in parent-child table in SQL Server with root ID?(如何使用根 ID 在 SQL Server 中的父子表中检索叶路径?)
Tsql union in while loop(while循环中的Tsql联合)
Pass a column as parameter to dateadd in SQL Server(将列作为参数传递给 SQL Server 中的 dateadd)
Is it possible to convert rows to a variable number of columns in T-SQL?(是否可以在 T-SQL 中将行转换为可变数量的列?)
Swap values between two rows of data(在两行数据之间交换值)