简体   繁体   中英

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:

<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. What would be the best way to get the DiscountType and DiscountAmount Out of the xml?

Thanks!

Please try the following.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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