Friday, July 3, 2009

xquery sqlserver2005 - ways to insert one xml node into another xml node

This post is all about inserting one xml node in to another using sqlserver 2005 xquery.
Example
Problem
declare @parentxml xml
declare @childxml xml
set @parentxml = '<employee> <firstname>nishant</firstname> </employee>'
set @childxml = '<lastname>khandhadia</lastname>'
-- if you try this way then it will sql will gave you error
-- i.e XQuery: SQL type 'xml' is not supported in XQuery.

set @parentxml.modify( 'insert sql:variable("@childxml") as last into (/employee) ' )
select @parentxml

Solusions

-- so now let see best way outs of this
--1) Creating temptable and finding way out.
declare @str_childxml nvarchar(100)
set @str_childxml = cast(@childxml as nvarchar(100))
create table #temp (tempDetails xml)
insert into #temp values (@parentxml)
exec ( N' update #temp set tempDetails.modify ( ''insert ' + @str_childxml + ' as last into (/employee)[1]'' )' )
select @parentxml = tempDetails from #temp
drop table #temp
select @parentxml


-- 2) This option is bit simple its just string concatination, this solution you can implement
-- if you know the structure of your xml.

declare @str_childxml nvarchar(100)
set @str_childxml = cast(@childxml as nvarchar(100))
SET @parentxml = '<employee><firstname>nishant</firstname>'+@str_childxml+'</employee>'select @parentxml


--3) This option is the best option as in first option you are creating temp table so it becomes bit heavy,
--in second option you should know the structure of your xml, but this way is the best as per me.
declare @ReturnXML xml
set @ReturnXML = convert(xml, (convert(nvarchar(max), @parentxml) + convert(nvarchar(max), @childxml)))
set @ReturnXML.modify('insert /*[2] as last into (/employee)[1]')
set @ReturnXML.modify('delete /*[2]')
select @ReturnXML

isn't it great if you have multiple solutions of one problem so that you can use one of then as per your need. Have a happy coding :)

No comments:

Post a Comment