2

I have a temp table with an XML column (XMLColumn) and a VARCHAR column (ABCColumn).

I am trying to replace the value of a particular XML node within XMLColumn with the value that is in ABCColumn of the same row. I need to do this for every row within the temp table. Is this possible to do without a cursor that would hold the replacement value for each fetch?

I have tried doing an update to the temp table using

XmlColumn.modify('replace value of ... with ...')

but I do not have a variable in this case. I need to get the value of a XYZColumn and use it as the replacement value. Every example I have seen either uses a variable or a hardcoded value - not a column value of the same row.

Also, I am using SQL Server 2005. Does anyone have any ideas?

2 Answers 2

5

Like This:

UPDATE  YourTable
SET     xml_col.modify(
    'replace value of (/root/val/text())[1] with sql:column("val_col")'
    )

(thanks to Andromar; I just edited his answer and used his SQLFiddle, (which works for this one too.))

Sign up to request clarification or add additional context in comments.

4 Comments

I just wrote and ran it on SQL 2005, so yes.
Awesome. For some reason, I was thinking that sql:column (and its other variations) were a 2008 thing.
AFAIK, they've been in SQL 2005 all along.
Well, you learn something new (and in this case very useful) every day. Thanks so much!
3

EDIT: I voted for RBarryYoung's answer, use that instead!

Only way I can think of is a cursor:

declare cur_t cursor for (select id, val_col from YourTable)
declare @id int
declare @val int
open cur_t

fetch cur_t into @id, @val
while @@fetch_status = 0
    begin
    update  YourTable
    set     xml_col.modify(
        'replace value of (/root/val/text())[1] with sql:variable("@val")')
    where   id = @id
    fetch cur_t into @id, @val
    end  

close cur_t
deallocate cur_t

Example at SQL Fiddle.

1 Comment

This is basically what I was doing before I decided to stop and ask if there was a better way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.