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

心不动则不痛 提交于 2019-12-25 04:30:05

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28575960/how-can-i-query-a-value-in-a-xml-column-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!