I have a table and I want to update one of its varchar fields based on the values in an another table.
I have the following table:
ID Constraint_Value
----------------------------
1 (OldVal_1) (OldVal_2)
2 (OldVal_2) (OldVal_1)
... and I want to use the data from the following table to make the update:
oldValue newValue
----------------------------
OldVal_1 NewVal_1
OldVal_2 NewVal_2
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
IF OBJECT_ID('tempdb..#tmpUpdates') IS NOT NULL DROP TABLE #tmpUpdates
GO
CREATE TABLE tempdb..#tmpUpdates ( oldValue varchar(256), newValue varchar(256))
GO
insert into #tmpConstraint
values (1, '(OldVal_1) (OldVal_2)')
insert into #tmpConstraint
values (2, '(OldVal_2) (OldVal_1)')
insert into #tmpUpdates
values ('OldVal_1', 'NewVal_1')
insert into #tmpUpdates
values ('OldVal_2', 'NewVal_2')
select * from #tmpConstraint
update c
set constraint_value = REPLACE(constraint_value, u.oldValue, u.newValue)
from #tmpConstraint c
cross join #tmpUpdates u
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 data in the lookup table?
UPDATEstatements - do they support recursive ones in that case? If so, you can probably write a CTE to assemble your newconstraint_value...value. Otherwise, the only thing I can think of would be to run the statement multiple times, so long as a row has an instance of an old value.