Link to home
Start Free TrialLog in
Avatar of nightshadz
nightshadzFlag for United States of America

asked on

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!
Avatar of TempDBA
TempDBA
Flag of India image

Avatar of nightshadz

ASKER

My XML looks like this -

<person firstName="Jon lastName="Johnson"></person>
Avatar of Anthony Perkins
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

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

The field is defined as AUDITLOG(text, null)
ASKER CERTIFIED SOLUTION
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial