简体   繁体   中英

Extracting value from XML in SQL Server

I'm trying to write a SQL Server query to select values from a XML column.

The column messagebody (type XML ) has content like this:

<?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 .

I've tried several solution 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.

Any suggestions?

You're not respecting the existing XML namespaces in your XML document! You need to include those in your XQuery - try this:

;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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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