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!
nightshadzAsked:
Who is Participating?
 
Anthony PerkinsCommented:
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

0
 
nightshadzAuthor Commented:
My XML looks like this -

<person firstName="Jon lastName="Johnson"></person>
0
 
Anthony PerkinsCommented:
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

0
 
nightshadzAuthor 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)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.