简体   繁体   English

从SQL Server中的XML中提取值

[英]Extracting value from XML in SQL Server

I'm trying to write a SQL Server query to select values from a XML column. 我正在尝试编写SQL Server查询以从XML列中选择值。

The column messagebody (type XML ) has content like this: messagebody (类型XML )包含如下内容:

<?xml version="1.0" encoding="utf-16"?>
<GetActivityUnemploymentGenerelEventType xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ActivityItem xmlns="http://service.bmuuuu/">
        <ActivityCoreItem xmlns="http://service.bmxxxx">
            <ActivityIdentifier xmlns="http://service.bmyyyy">d5ck7132-703c-1234-8099-963b35b24bc5</ActivityIdentifier>
            <StartDate xmlns="http://service.bmaaa">2016-01-25</StartDate>

I'm trying to nail the value of startdate and ActivityIdentifier . 我试图确定startdateActivityIdentifier的值。

I've tried several solution fx: 我试过几个解决方案fx:

SELECT XML.query('messagebody(/GetActivityUnemploymentGenerelEventType/ActivityItem/ActivityCoreItem/ActivityIdentifier)')
FROM table

SELECT messagebody.value('(/GetActivityUnemploymentGenerelEventType/ActivityCoreItem/ActivityIdentifier/Value)[1]', 'int')
FROM table

SELECT messagebody.value('(/GetActivityUnemploymentGenerelEventType//ActivityCoreItem/ActivityIdentifier())[1]', 'nvarchar(max)')
FROM table

Query result: 查询结果:

Cannot find either column "messagebody" or the user-defined function or aggregate "messagebody.value", or the name is ambiguous. 找不到列“messagebody”或用户定义的函数或聚合“messagebody.value”,或者名称不明确。

Any suggestions? 有什么建议?

You're not respecting the existing XML namespaces in your XML document! 您不尊重XML文档中现有的XML命名空间 You need to include those in your XQuery - try this: 你需要在XQuery中包含这些 - 试试这个:

;WITH XMLNAMESPACES ('http://service.bmuuuu/' AS ns1, 
                     'http://service.bmxxxx' AS ns2, 
                     'http://service.bmyyyy' as ns3, 
                     'http://service.bmaaa' as ns4)
SELECT
    ActivityIdentifier = xc.value('(ns3:ActivityIdentifier)[1]', 'varchar(100)'),
    StartDate = xc.value('(ns4:StartDate)[1]', 'varchar(25)')
FROM 
    dbo.YourTable
CROSS APPLY
    MessageBody.nodes('/GetActivityUnemploymentGenerelEventType/ns1:ActivityItem/ns2:ActivityCoreItem') AS XT(XC)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM