nightshadz
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!
I'm using SQL Server 2008.
Thanks!
ASKER
My XML looks like this -
<person firstName="Jon lastName="Johnson"></perso n>
<person firstName="Jon lastName="Johnson"></perso
Unfortunately that is not well-formed Xml. In order for it to be well formed it needs to be:
<person firstName="Jon" lastName="Johnson"></perso n>
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('perso n') T(C)
This is how I tested it:
<person firstName="Jon" lastName="Johnson"></perso
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('perso
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
ASKER
Must have missed that extra quote - I meant to type <person firstName="Jon" lastName="Johnson"></perso n>.
The field is defined as AUDITLOG(text, null)
The field is defined as AUDITLOG(text, null)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
http://stackoverflow.com/questions/899313/select-values-from-xml-field-in-sql-server-2008