We help IT Professionals succeed at work.

SQL Help - How do I query a value out of a field that has XML?

I have a text field in a table where the data is stored in XML.  Is there an easy way through SQL statements to query this data?  

I'm using SQL Server 2008.

Thanks!
Comment
Watch Question

Author

Commented:
My XML looks like this -

<person firstName="Jon lastName="Johnson"></person>
Top Expert 2012

Commented:
Unfortunately that is not well-formed Xml.  In order for it to be well formed it needs to be:
<person firstName="Jon" lastName="Johnson"></person>
 
Also we need some clarity to the question:
"I have a text field in a table where the data is stored in XML."
So is it text or Xml data type?

If it is Xml than it is as simple as (fix the obvious typos in xSELECT, xDECLARE and xINSERT):
xSELECT      T.C.value('@firstName', 'varchar(20)'),
      T.C.value('@lastName', 'varchar(20)')
FROM      YourTableName
      CROSS APPLY YourXmlColumn.nodes('person') T(C)

This is how I tested it:
xDECLARE @T TABLE (MyXml Xml)

xINSERT @T (MyXml) VALUES ('<person firstName="Jon" lastName="Johnson"></person>')

xSELECT	T.C.value('@firstName', 'varchar(20)'),
	T.C.value('@lastName', 'varchar(20)')
FROM	@T
	CROSS APPLY MyXml.nodes('person') T(C)

Output:
(No column name)	(No column name)
Jon	Johnson

Open in new window

Author

Commented:
Must have missed that extra quote - I meant to type <person firstName="Jon" lastName="Johnson"></person>.

The field is defined as AUDITLOG(text, null)
Top Expert 2012
Commented:
Then you will have to use a derived table as follows:

SELECT  T.C.value('@firstName', 'varchar(20)'),
             T.C.value('@lastName', 'varchar(20)')
FROM    (SELECT CAST(MyXml AS XML) MyXml FROM YourTable) t1
            CROSS APPLY MyXml.nodes('person') T (C)


This is how I tested it:
DECLARE @T TABLE (MyXml TEXT)

INSERT  @T(MyXml) VALUES ('<person firstName="Jon" lastName="Johnson"></person>')

SELECT  T.C.value('@firstName', 'varchar(20)'),
        T.C.value('@lastName', 'varchar(20)')
FROM    (SELECT CAST(MyXml AS XML) MyXml FROM @T) t1
        CROSS APPLY MyXml.nodes('person') T (C)

Output:
(No column name)	(No column name)
Jon	Johnson

Open in new window