user55474
user55474

Reputation: 537

SQL Server xml copy values of one node to another

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

Upvotes: 1

Views: 2466

Answers (2)

Gabriel McAdams
Gabriel McAdams

Reputation: 58261

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

Upvotes: 2

user55474
user55474

Reputation: 537

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

Upvotes: 0

Related Questions