Wednesday, 11 September 2013

Extracting child node in from XML using T-SQL

Extracting child node in from XML using T-SQL

I'm stuck on trying to get the 'availability' node's value out of an
envelope returned via T-SQL from a Microsoft Lync database. The usual
methods of .value('(/MyElement/Something)[1]') doesn't seem to work for
me.
<state xsi:type="aggregateState"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/2006/09/sip/state">
<availability>3500
</availability>
<delimiter xmlns="http://schemas.microsoft.com/2006/09/sip/commontypes" />
<timeZoneBias>-60
</timeZoneBias>
<timeZoneName>GMT Daylight Time
</timeZoneName>
<timeZoneAbbreviation>GMT Daylight Time
</timeZoneAbbreviation>
<device>computer
</device>
<end xmlns="http://schemas.microsoft.com/2006/09/sip/commontypes" />
</state>
This is the query I've been experimenting with:
SELECT TOP 1
CAST(SUBSTRING(i.Data, 0, 4000) as
XML).value('(/state//availability)[1]', 'varchar(256)')
FROM dbo.PublishedCategoryInstanceView AS i
INNER JOIN dbo.CategoryDef AS d
ON (d.CategoryId = i.CategoryId)
WHERE i.PublisherId = (SELECT ResourceId FROM dbo.Resource
WHERE UserAtHost = 'my.email@mydomain.local')
ORDER BY i.LastPubTime DESC
All I get back is 'NULL' unless I do CAST(SUBSTRING(i.Data, 0, 4000) as
XML).value('(/)[1]', 'varchar(256)') which returns 3500-60GMT Daylight
TimeGMT Daylight Timecomputer
I do know that when I strip out the three attributes on the state element
I can perform normal XML queries against the data so I can get around this
by manipulating the string with a few replace statements but I'd rather
learn exactly what I'm doing wrong here, if anyone can help?

No comments:

Post a Comment