我有下表:
Id Account_Number Csd_id pk_id dk_id
1 343 200 100 50
2 234 400 200 70
3 343 400 100 70
我对account_number
,csd_id
和pk_id
有一个独特的约束。
现在,我想将所有csd_id
更新为200
csd_id
400
,只有在未违反上述唯一约束的情况下才会{。}}。
更新完成后,我必须删除csd_id
为400
的剩余记录。
答案 0 :(得分:2)
您只需要一个包含update
子句的not exists
语句,以避免违反约束的更新。当然,对于左上行,您需要一个简单的delete
语句:
update tbl t1
set t1.csd_id = 200
where t1.csd_id = 400
and not exists (
select null
from tbl t2
where t2.account_number = t1.account_number
and t2.pk_id = t1.pk_id
and t2.csd_id = 200
);
delete tbl where csd_id = 400;
修改强>
非常不可能,但如果account_number
或pk_id
都可以为空:
update tbl t1
set t1.csd_id = 200
where t1.csd_id = 400
and not exists (
select null
from tbl t2
where (t2.account_number = t1.account_number or (t2.account_number is null and t1.account_number is null))
and (t2.pk_id = t1.pk_id or (t2.pk_id is null and t1.pk_id is null))
and t2.csd_id = 200
);
delete tbl where csd_id = 400;