简体   繁体   中英

SQL Server 2012 query XML column

I have done a lot of researching on the net for the answer to this question. I have found a lot of help sites but I'm not getting the results unfortunately (I don't really understand XML).

I have a table (called CustomField.PersonCustomFieldValue) that has an XML datatype column (called XmlValue) which stores XML data. I am unsure how to extract the values.

An example of the data stored in the column is:

<XmlDataValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Value xsi:type="xsd:string">NO</Value></XmlDataValue>

How do extract the Value string? In this case - "No".

Thanks very much.

Try it like this:

DECLARE @xml XML=
N'<XmlDataValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Value xsi:type="xsd:string">NO</Value>
</XmlDataValue>';
SELECT @xml.value(N'(/XmlDataValue/Value/text())[1]',N'nvarchar(max)');

This will return the same

SELECT @xml.value(N'(//Value)[1]',N'nvarchar(max)')

But you should always be as specific as possible!

Calling this for a table's column looks like this:

SELECT XmlValue.value(N'(/XmlDataValue/Value/text())[1]',N'nvarchar(max)')
FROM YourTable

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