SQL Server - 查询缺少命名空间的XML列

时间:2013-03-14 00:13:58

标签: sql-server xml namespaces

这个问题看起来真的很讨厌。我在名为“Message”的列中有以下小XML,我想查询它。我遇到的问题是“ClaimData”元素。如您所见,它将其名称空间设置为空字符串。

<DataExchange xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://schemas.abc.com/library/DataExchange">
  <Data>
      <ClaimData xmlns="">
          <CurrentClaimNumber>TEST0000319001</CurrentClaimNumber>
      </ClaimData>
  </Data>
</DataExchange>      

下面的查询返回XML列的NULL值,因为ClaimData元素使用空命名空间,我不知道如何在XML列的查询中指出这一点。

有人可以提供一个工作(并且希望经过测试)的例子,说明如何在XML Message列中查询“CurrentClaimNumber”元素(它是“ClaimData”的子元素)?

非常非常感谢。

WITH XMLNAMESPACES (
     'http://www.w3.org/2001/XMLSchema' AS "xsd",
    'http://www.w3.org/2001/XMLSchema-instance' AS "xsi",
     DEFAULT 'http://schemas.rising.com/library/DataExchange'
) SELECT [StoredMessageID],
    Message.value('(/DataExchange/Data/ClaimData/CurrentClaimNumber)[1]', 'CHAR(750)')
  FROM [DataExchange].[dbo].[MessageStorage]

1 个答案:

答案 0 :(得分:3)

如何将默认命名空间分配给前缀,以便您可以使用null命名空间而不使用空命名空间?这可能是唯一的选择:

WITH XMLNAMESPACES (
     'http://www.w3.org/2001/XMLSchema' AS "xsd",
    'http://www.w3.org/2001/XMLSchema-instance' AS "xsi",
     'http://schemas.abc.com/library/DataExchange' AS "de"
) SELECT [StoredMessageID],
    Message.value('(/de:DataExchange/de:Data/ClaimData/CurrentClaimNumber)[1]', 
                                                                         'CHAR(750)')
  FROM [DataExchange].[dbo].[MessageStorage]

验证如下:

insert into MessageStorage values('
<DataExchange
   xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://schemas.abc.com/library/DataExchange">
  <Data>
      <ClaimData xmlns="">
          <CurrentClaimNumber>TEST0000319001</CurrentClaimNumber>
      </ClaimData>
  </Data>
</DataExchange>');


WITH XMLNAMESPACES (
     'http://www.w3.org/2001/XMLSchema' AS "xsd",
    'http://www.w3.org/2001/XMLSchema-instance' AS "xsi",
     'http://schemas.abc.com/library/DataExchange' AS "de"
) SELECT [StoredMessageID],
    Message.value('(/de:DataExchange/de:Data/ClaimData/CurrentClaimNumber)[1]', 
                                                                         'CHAR(750)')
  FROM [dbo].[MessageStorage]

结果:

 1     TEST0000319001