查找XML是否包含,然后返回一些东西



我正在尝试找到一种方法,以便我运行查询以检查XML文件是否包含某些内容(如果为true(,将我返回该XML中的其他标签。示例:

<shop>
   <item>
       <Product>shirt</Product>
       <color>red</color>
   </item>
   <item>
       <Product>shirt</Product>
       <color>yellow</color>
   </item>
   <item>
       <Product>jeans</Product>
       <color>blue</color>
   </item>
</shop>

假设col名称是XML,我可以找到所有带衬衫的Col,我想获得衬衫的颜色

[XML].exist ('/shop/item/Product[contains(., "shirt")]') > 0);

我希望能够获得一张桌子或衬衫颜色的阵列。那可能吗?我正在使用SQL 2012

item元素上切碎xml,因为我们需要从每个xml中选择多个 color

SELECT P.I.value('color[1]', 'varchar(100)') AS shirt_color
FROM YourTable t
CROSS APPLY t.[XML].nodes('/shop/item[contains(Product[1], "shirt")]') as P(I)

rextester demo

还要注意,通过使用CROSS APPLY和XPath/Xquery,没有任何"衬衫"项目的行被过滤出来,因此我们不再需要上述exist()

最新更新