简体   繁体   中英

How can I query a value in a XML column in SQL Server 2008

I have following XML stored in a XML column in a SQL Server database table.

<?xml version="1.0" encoding="UTF-8" ?>
<ns0:Root>
    <ns0:Result>
        <ns0:AStatus>Aaa</ns0:AStatus>
        <ns0:BStatus>Bbb</ns0:BStatus>
    </ns0:Result>
</ns0:Root>

I'd like to get value "Aaa", by firing SQL query.

Your XML data is incomplete - it uses a namespace prefix ns0 without defining it anywhere... I've added some arbitrary, totally made-up XML namespace here in my sample - you need to check what that XML namespace actually is in your case and adapt the sample accordingly!

Try this:

DECLARE @InputTable TABLE (ID INT NOT NULL, XmlData XML)

INSERT INTO @InputTable(ID, XmlData) VALUES(42, '<?xml version="1.0" encoding="UTF-8" ?>
<ns0:Root xmlns:ns0="urn:some-sample-xml-namespace">
    <ns0:Result>
        <ns0:AStatus>Aaa</ns0:AStatus>
        <ns0:BStatus>Bbb</ns0:BStatus>
    </ns0:Result>
</ns0:Root>')

-- define the XML namespace to use     
;WITH XMLNAMESPACES('urn:some-sample-xml-namespace' AS x)
SELECT 
    ID,
    XC.value('(x:AStatus)[1]', 'varchar(50)') 
FROM    
    @inputtable
CROSS APPLY
    -- get a "pseudo" table of nodes <ns0:Root>/<ns0:Result>
    XmlData.nodes('x:Root/x:Result') AS XT(XC)

Basically, you need to have a definition for your XML namespace prefix - and in the SELECT against this XML data, you need to have the same XML namespace (even though - as shown - the prefix assigned to that namespace can be different - but the namespace must match!).

This then selects the data from the table, and for the XML data, it uses the .nodes() XQuery function to get a list of XML element that match this XPath expression - and it gets these nodes as a in-memory pseudo table XT with a single XML column XC from which you can then again fetch values (like reaching into the first <ns:AStatus> element).

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