首页 > 解决方案 > 从 SQL Server 数据库中的 XML 列中提取数据值

问题描述

我有一个 SQL Server 数据库,其中包含一个包含XML列的表。我想从中提取数据,但我们在名称上使用前缀。

这是一个例子:

<cfdi:comprobante xmlns:cfdi="" total="" tax="">
     <cfdi:sender information="" moreinformation=""/>
     <cfdi:receiver information="" moreinformation=""/>
     <cfdi:addments>
            <another:payment information="" moreinformation="">
                <another:Movements date="" description="hello" amount="100.00" contract="10"/>
                <another:Movements date="" description="hello2" amount="200.00" contract="20"/>
                <another:Movements date="" description="bye" amount="300.00" contract="30"/>
                <another:Movements date="" description="bye2" amount="400.00" contract="40"/>
            </another:payment>
     </cfdi:addments>
</cfdi:comprobante>

我需要的是一个查询,它可以提取如下所示的运动:

ID(其他列 合同 数量 描述
39098 10 100.00 你好
39098 20 200.00 你好2
39098 30 300.00 再见
39098 40 400.00 再见2

我希望我足够清楚。请在这方面真的需要帮助。

先感谢您。

标签: sql-serverxml

解决方案


你需要这样的东西——考虑到定义的 XML 命名空间;我无法显示确切的代码,因为您没有向我们展示定义 XML 命名空间的位置(xmlns:cfdi="sat.gob.mx/cfd/3"xmlns:another="pegasotecnologia.com/secfd/Schemas"):

WITH XMLNAMESPACES('sat.gob.mx/cfd/3' AS c,
                   'pegasotecnologia.com/secfd/Schemas' AS a)
SELECT 
    ID,
    XC.value('@contract', 'int'),
    XC.value('@amount', 'decimal(16,2)'),
    xc.value('@description', 'varchar(100)')
FROM 
    dbo.YourTable
CROSS APPLY 
    XmlColumn.nodes('/c:comprobante/c:addments/a:payment/a:Movements') AS XT(XC)

如果你得到正确的 XML 命名空间,你应该得到类似这样的输出:

在此处输入图像描述


推荐阅读