问题
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