仅在未违反唯一约束时更新表

时间:2016-08-28 22:10:04

标签: sql database oracle

我有下表:

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_numbercsd_idpk_id有一个独特的约束。

现在,我想将所有csd_id更新为200 csd_id 400,只有在未违反上述唯一约束的情况下才会{。}}。

更新完成后,我必须删除csd_id400的剩余记录。

1 个答案:

答案 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_numberpk_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;