I have a table regionkey:
areaid -- primary key, int
region -- char(4)
locale -- char(4)
The entire rest of the database is foreign-keyed to areaid. In this table there is an index on (region, locale) with a unique constraint.
The problem is that I have two records:
101 MICH DETR
102 ILLI CHIC
And I need to swap the (region,locale) fields between them, so that I wind up with:
101 ILLI CHIC
102 MICH DETR
The naive approach won’t work because it violates the unique index on region and locale:
update regionkey
set region='ILLI', locale='CHIC' where areaid = 101; -- FAILS
update regionkey
set region='MICH', locale='DETR' where areaid = 102;
How can I do this? Is there an atomic way to make the swap? Suggestions?
You can’t defer constraint checks in SQL Server over multiple statements (unless you DISABLE) so you have to avoid the conflict or do it in one statement
or, more conventionally (in a transaction this one)
Edit: Why not swap keys not values? It usually achieves the sane result unless areaid has some meaning