tags:

views:

187

answers:

2

Hi I want to copy the values of one node to another in sql server(2005 and 2008). e.g if one of the xml data is as below

 <Data>
<Name></Name>
<ShortName>Joe</ShortName>
</Data>

the resulting xml should be

<Data>
<Name>Joe</Name>
<ShortName>Joe</ShortName>

the update statement should affect all the rows in the table

appreciate any help thanks

A: 

got the solution update table set col.modify(replace value of (/Name/text())[1] with (/ShortName/text())[1])

There is an error in your solution. See my answer for more information.
Gabriel McAdams
+1  A: 

You have to watch out for Silent XQuery failures.

The problem in this case is that XPath expression (/Data/Name/text())1 returns an empty sequence. ‘Name’ is an empty element (It has no children). Therefore the expression (/Data/Name/text())1 doesn’t point to any existing node. The solution to this problem is to insert a new text node inside the Name element, like this:

DECLARE @myDoc xml
SET @myDoc = '<Data>
    <Name></Name>
    <Name2>dd</Name2>
    <ShortName>Joe</ShortName>
</Data>'

SELECT @myDoc

if (@myDoc.exist('(/Data/Name/text())[1]') = 1) BEGIN
    set @myDoc.modify('
        replace value of (/Data/Name/text())[1]
        with (/Data/ShortName/text())[1]
    ')
end else begin
    set @myDoc.modify('
        insert (/Data/ShortName/text())[1]
        as first into (/Data/Name)[1]
    ')
end

SELECT @myDoc
Gabriel McAdams
great tip. i did encounter this issue but forgot to mention it in the post.
I'm glad you caught it. Don't forget to accept this answer if you found it useful.
Gabriel McAdams