将XML节点作为SQL Server中的行读取

时间:2017-08-21 16:03:59

标签: sql xml xquery

我将以下XML存储在表的XML列中:

<MessageResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <MessageContainer>
    <DocumentType xmlns="urn:www:bebe:de:b2b:v01">Testdata</DocumentType>
    <Payload xmlns="urn:www:bebe:de:b2b:v01">
      <Testdata xmlns:ns0="un:unece:260:data:ron_data:v1">
        <PayloadResponseEvent>
          <Identification>2970729807</Identification>
          <StatusType listAgencyIdentifier="6">accepted</StatusType>
          <OriginalDocument>2769262</OriginalDocument>
        </PayloadResponseEvent>
        <PayloadResponseEvent>
           <Identification>2970729809</Identification>
          <StatusType listAgencyIdentifier="6">rejected</StatusType>
          <OriginalDocument>2769269</OriginalDocument>
        </PayloadResponseEvent>
      </Testdata>
    </Payload>
  </MessageContainer>
</MessageResponse>

我想创建一个select,其中我根据PayloadResponseEvent获取列,如:

Identification        StatusType    OriginalDocument
----------------------------------------------------
2970729807            accepted      2769262
2970729809            rejected      2769269

我已经尝试了许多基于节点和值的不同SQL / XML语句,但找不到获取此数据的简便方法。名称空间也在阻碍。

有人可以为此提供解决方案吗?

由于

1 个答案:

答案 0 :(得分:1)

WITH XMLNAMESPACES (DEFAULT 'urn:www:bebe:de:b2b:v01')
SELECT 
    d.p.value('./Identification[1]', 'BIGINT') AS [Identification]
    ,d.p.value('./StatusType[1]', 'NVARCHAR(100)') AS [StatusType]
    ,d.p.value('(./StatusType/@listAgencyIdentifier)[1]', 'int') AS [ListAgencyIdentifier]
    ,d.p.value('./OriginalDocument[1]', 'BIGINT') AS [OriginalDocument]
FROM [yourtable] [t]
CROSS APPLY [t].[yourcolumn].nodes('//PayloadResponseEvent') AS d(p)