简体   繁体   English

使用SQL Server选择XML节点

[英]Selecting XML nodes with SQL Server

My XMLData is stored under table.[column] : dbo.promotions.[PromotionDiscountData] and the XML looks like the following when i expand it: 我的XMLData存储在table。[column]下:dbo.promotions。[PromotionDiscountData],当我扩展它时,XML如下所示:

<ArrayOfPromotionDiscountBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PromotionDiscountBase xsi:type="OrderPromotionDiscount">
    <DiscountType>Fixed</DiscountType>
    <DiscountAmount>5.0000</DiscountAmount>
  </PromotionDiscountBase>
</ArrayOfPromotionDiscountBase>

I would like to export a report and flatten out the xml as a column with everything else in the dbo.promotions table. 我想导出报告,并将xml整理为dbo.promotions表中其他所有内容的列。 What would be the best way to get the DiscountType and DiscountAmount Out of the xml? 从XML中获取DiscountType和DiscountAmount的最佳方法是什么?

Thanks! 谢谢!

Please try the following. 请尝试以下方法。

SQL 的SQL

-- DDL and data population, start
DECLARE @tbl TABLE (ID INT IDENTITY(1,1) PRIMARY KEY,[xmlData] XML NOT NULL);

INSERT INTO @tbl([xmlData])
VALUES 
(N'<ArrayOfPromotionDiscountBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PromotionDiscountBase xsi:type="OrderPromotionDiscount">
    <DiscountType>Fixed</DiscountType>
    <DiscountAmount>5.0000</DiscountAmount>
  </PromotionDiscountBase>
</ArrayOfPromotionDiscountBase>');
-- DDL and data population, end

SELECT ID
    , col.value('(DiscountType)[1]', 'VARCHAR(30)') AS [DiscountType]
    , col.value('(DiscountAmount)[1]', 'DECIMAL(10,4)') AS [DiscountAmount]
FROM @tbl AS tbl
      CROSS APPLY tbl.[xmlData].nodes('/ArrayOfPromotionDiscountBase/PromotionDiscountBase') AS tab(col);

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

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