3

I have a table in Sql server that stores Xml data in one of its columns. The Xml column data looks like this:

<TestDef Weight="0" FailValue="2" ConceptID="-327">
  <ToleranceDef ObjectType="SomeName" TargetValue="0"TargetRange="2" />
</TestDef>

I need to write a query that fetches out all the conceptId's from each rows Xml column. Here it would be -327

I know I can cast the Xml column to a nvarchar(max) then use some reg exp to get the value but not sure how to use the regular expression

1 Answer 1

5

Here's an example using a table variable. It will be the same concept with an actual table:

Declare @XmlTable table (
    Id Integer Identity,
    XmlValue XML
)

Insert Into @XmlTable (XmlValue) values ('<TestDef Weight="0" FailValue="2" ConceptID="-327"><ToleranceDef ObjectType="SomeName" TargetValue="0" TargetRange="2" /></TestDef>')
Insert Into @XmlTable (XmlValue) values ('<TestDef Weight="0" FailValue="2" ConceptID="-325"><ToleranceDef ObjectType="SomeName" TargetValue="0" TargetRange="2" /></TestDef>')


select
    Id,
    XmlValue,
    XmlValue.value('(/TestDef/@ConceptID)[1]', 'integer') as ConceptId
from
    @XmlTable
2
  • 1
    instead of using a table varible for your demo you might want to try SQL Fiddle Commented Jul 25, 2013 at 16:22
  • Thanks for the tip, definitely looks like a useful site!
    – Josh Jay
    Commented Jul 25, 2013 at 16:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.