简体   繁体   English

xml nodes() in tsql - 匹配父节点和子节点属性

[英]xml nodes() in tsql - matching parent nodes with child node attributes

I am trying to query following xml structure:我正在尝试查询以下 xml 结构:

<effect><![CDATA[<p>some text</p>]]>
  <product code="4298271" />
  <product code="4298273" />
  <product code="4298274" />
  <product code="4298275" />
  <product code="4298276" />
</effect>
<effect><![CDATA[<p>some other text</p>]]>
  <product code="5298271" />
  <product code="5298273" />
  <product code="5298274" />
  <product code="5298275" />
  <product code="5298276" />
</effect>

I need to transform this data to a table like below:我需要将此数据转换为如下表:

Effect   ProductCode

some text       4298271
some text       4298273
some text       4298274
...
...

Is it even possible?甚至可能吗? I can get the list of product rows which are under every effect parent but no idea how to match it with the effect header from which the text should be queried.我可以获得每个效果父级下的产品行列表,但不知道如何将其与应从中查询文本的效果 header 匹配。

Let's say that effect is root node for simplifying.假设效果是简化的根节点。

Even though the XML isn't really a valid document - you can still query it in T-SQL using XQuery - something like this:即使 XML 不是真正有效的文档 - 您仍然可以使用 XQuery 在 T-SQL 中查询它 - 如下所示:

DECLARE @input XML = '<effect><![CDATA[<p>some text</p>]]>
  <product code="4298271" />
  <product code="4298273" />
  <product code="4298274" />
  <product code="4298275" />
  <product code="4298276" />
</effect>
<effect><![CDATA[<p>some other text</p>]]>
  <product code="5298271" />
  <product code="5298273" />
  <product code="5298274" />
  <product code="5298275" />
  <product code="5298276" />
</effect>'

SELECT
    xc.value('(../text())[1]', 'varchar(50)'),
    xc.value('(@code)[1]', 'int')
FROM
    @input.nodes('/effect/product') AS XT(XC)

This produces an output:这将产生一个 output:

在此处输入图像描述

Adjust as needed....根据需要调整......

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

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