解析表MSSQL服务器中保存的xml

时间:2018-11-06 08:43:56

标签: sql sql-server xml xml-namespaces

我有一个表,该表的列名为xml。表是文本类型,但包含xml响应。我需要此列中的2个值:

    来自PL81300032102
  • <ie801:Traderid>
  • Some Company sp. z o.o.来自<ie801:TraderName>

是否可以在SQL Server中使用查询?

<?xml version="1.0" encoding="UTF-8"?><EMCSToTrader xmlns="urn:publicid:-:PL:GOV:MF:EMCS:PHASE3:EMCS-TRADER:REQUEST:V1.00" xmlns:ie801="urn:publicid:-:EC:DGTAXUD:EMCS:PHASE3:IE801:V1.51" xmlns:tms="urn:publicid:-:EC:DGTAXUD:EMCS:PHASE3:TMS:V1.51" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Message><ie801:IE801>
<ie801:Header>
  <tms:MessageSender>NDEA.PL</tms:MessageSender>
  <tms:MessageRecipient>PL61300032004</tms:MessageRecipient>
  <tms:DateOfPreparation>2018-07-17</tms:DateOfPreparation>
  <tms:TimeOfPreparation>11:16:44.631</tms:TimeOfPreparation>
  <tms:MessageIdentifier>PL#IE801#69474394</tms:MessageIdentifier>
</ie801:Header>
<ie801:Body>
  <ie801:EADContainer>
    <ie801:ConsigneeTrader language="pl">
      <ie801:Traderid>PL81300032102</ie801:Traderid>
      <ie801:TraderName>Some Company sp. z o.o.</ie801:TraderName> <...>

表结构:

Screenshot of table structure

我能够使用以下方法将文本数据转换为xml类型:

SELECT TOP (10) * FROM (
    SELECT CAST([xml] AS XML) AS xmlcontent 
    FROM [emcskomunikaty]
) det

现在尝试从xml中获取价值。

1 个答案:

答案 0 :(得分:1)

我想您可以这样做:

SELECT
    xmldata.value('declare namespace ns1="urn:publicid:-:EC:DGTAXUD:EMCS:PHASE3:IE801:V1.51"; (//ns1:Traderid)[1]', 'VARCHAR(100)') AS Traderid,
    xmldata.value('declare namespace ns1="urn:publicid:-:EC:DGTAXUD:EMCS:PHASE3:IE801:V1.51"; (//ns1:TraderName)[1]', 'VARCHAR(100)') AS TraderName
FROM @t
CROSS APPLY (SELECT CAST(xml AS XML)) AS CA(xmldata)

这里唯一棘手的部分是处理名称空间。如果您选择忽略命名空间,则只需使用//*:Traderid