I have a table and I want to update one of its varchar fields based on the values in an XML parameter.
I have the following table:
ID Constraint_Value
1 (OldVal_1) (OldVal_2)
2 (OldVal_2) (OldVal_1)
and I want to use the following XML to update the Constraint_Value field:
<qaUpdates>
<qaUpdate><old>OldVal_1</old><new>NewVal_1</new></qaUpdate>
<qaUpdate><old>OldVal_2</old><new>NewVal_2</new></qaUpdate>
</qaUpdates>
After the update, I am aiming for the following:
ID Constraint_Value
1 (NewVal_1) (NewVal_2)
2 (NewVal_2) (NewVal_1)
The following SQL illustrates my problem (which you can run in SQL Management Studio without any set up) :
IF OBJECT_ID('tempdb..#tmpConstraint') IS NOT NULL DROP TABLE #tmpConstraint
GO
CREATE TABLE tempdb..#tmpConstraint ( constraint_id INT PRIMARY KEY, constraint_value varchar(256) )
GO
insert into #tmpConstraint
values (1, '(OldVal_1) (OldVal_2)')
insert into #tmpConstraint
values (2, '(OldVal_2) (OldVal_1)')
select * from #tmpConstraint
declare @myXML XML
set @myXML = N'<qaUpdates>
<qaUpdate><old>OldVal_1</old><new>NewVal_1</new></qaUpdate>
<qaUpdate><old>OldVal_2</old><new>NewVal_2</new></qaUpdate>
</qaUpdates>'
update c
set constraint_value = REPLACE(constraint_value, Child.value('(old)[1]', 'varchar(50)'), Child.value('(new)[1]', 'varchar(50)'))
from #tmpConstraint c
cross join @myXML.nodes('/qaUpdates/qaUpdate') as N(Child)
select * from #tmpConstraint
This gives the results:
(Before)
1 (OldVal_1) (OldVal_2)
2 (OldVal_2) (OldVal_1)
(After)
1 (NewVal_1) (OldVal_2)
2 (OldVal_2) (NewVal_1)
As you can see just OldVal_1 has been updated. OldVal_2 has remained the same.
How do I update the field with all the elements specified in the xml parameter?