Monday, February 27, 2012

How can I get value of XML element from XML column

I have one simple question. How can I get scalar value of en XML element from XML column?

...

<tag> value <tag/>

...

I wont to get a result: "value"

this runs against a XML variable, but afaik, it should work in a similar manner:

set nocount on
DECLARE @.xVar XML
declare @.docHandle int
SET @.xVar =
'<book genre="security" publicationdate="2002" ISBN="0-7356-1588-2">
<title>Writing Secure Code</title>
<author>
<FirstName>Michael</FirstName>
<LastName>Howard</LastName>
</author>
<author>
<FirstName>David</FirstName>
<LastName>LeBlanc</LastName>
</author>
<price>39.99</price>
</book>'

SELECT
nref.value('FirstName[1]', 'nvarchar(50)') FirstName,
nref.value('LastName[1]', 'nvarchar(50)') LastName
FROM @.xVar.nodes('/book/author') AS R(nref)
|||or you could simple do this..seems more concise to me

declare @.xml nvarchar(100)
declare @.id int

set @.xml = '<tag> value </tag>'

exec sp_xml_preparedocument @.id output, @.xml
select tagVal from openxml(@.id, N'//tag') with (tagVal varchar(100) 'text()')|||

Don't forget the :

exec sp_xml_removedocument @.Id

It is an alternative. I'm currently looking at code to try and determine whether the .nodes methods available are faster/the same/slower than OPENXML.

|||

The nodes() method on an indexed column is faster/same than doing server side cursors. It also scales better w.r.t. memory usage.

OpenXML is faster on parameters/variables than nodes(), but less scalable.

Best regards

Michael

No comments:

Post a Comment