带有XML数据的SQL查询列

时间:2015-04-08 17:05:43

标签: sql xml sql-server-2008

我在列中有以下数据,如何查询其中的值。

<deliveryPart notificationId="12345">
    <message address="email@email.com" content="multipart/alternative" domain="email.com" format="0" id="159436637" recipient-id="098765" targetCode="__MAIN__">
        <custom>
            <recipient Nickname="mynickname" id="54321" />
            <targetData Incident_Id="1509403" reference_nb="0000-0000" />
        </custom>
    </message>
</deliveryPart>

我快速去了,但我以前从未做过,而且时间不长。

select top 10 *
from [db].[db].[table]
where mData.value('(deliveryPart/message/recipient-id)[1]','varchar(max)') like '098765'

我收到以下错误

  

Msg 4121,Level 16,State 1,Line 1
  找不到列&#34; mData&#34;或用户定义的函数或聚合&#34; mData.value&#34;,或名称不明确。

更新

我使用以下代码来获取xml值并且它可以正常工作

SELECT TOP 1000 B1.[mData].value('(deliveryPart/message/@id)[1]', 'NVARCHAR(MAX)') AS 'MessageID', B1.[mData].value('(deliveryPart/message/@address)[1]', 'NVARCHAR(MAX)') AS 'Address'
  FROM (SELECT CAST(mData as XML) as xmlData FROM [dbo].[db].[table]) B0
  CROSS APPLY xmlData.nodes('/') B1 (mData)
  WHERE B1.[mData].value('(deliveryPart/message/@address)[1]', 'NVARCHAR(MAX)') LIKE '%@%'

它返回ntext字段中的xml值存储就好了。

180646774   email1@email.com
159436627   test2@hotmail.com
159436637   test3@hotmail.com

但是,我需要从mData列外部获取值,并且不允许我这样做。

1 个答案:

答案 0 :(得分:1)

您需要将@recipient-id用作XML 属性 - 而不是XML元素:

<message address="email@email.com" content="multipart/alternative" 
         domain="email.com" format="0" id="159436637" 
         recipient-id="098765" targetCode="__MAIN__">
         ************  this is an *attribute* - use the `@` to select it!

代码:

select top 10 *
from [db].[db].[table]
where mData.value('(deliveryPart/message/@recipient-id)[1]', 'varchar(max)') like '098765'