PL / SQL:在更新尝试时,删除导致unique_violation异常的行

时间:2017-11-30 16:57:07

标签: sql postgresql exception sql-delete

我正在尝试以下列方式更新表,并获得预期的unique_violation异常

my.db=# UPDATE my_table SET code = REPLACE(code, ‘abd’, ‘abc’);
ERROR:  duplicate key value violates unique constraint "my_table_pkey"
DETAIL:  Key (code, group_id)=(abc, 1) already exists.

我知道我需要删除不正确的行而不是更新它,如果它导致此异常,所以我尝试写下面的内容

DO $$ 
    BEGIN
        UPDATE my_table SET code = REPLACE(code, ‘abd’, ‘abc’);
    EXCEPTION
        WHEN unique_violation THEN
            DELETE FROM my_table WHERE code = ‘abd’ AND group_id = ?;
END $$;

如何仅删除导致引发异常的行并确保我的更新继续在所有其他条目上运行?

1 个答案:

答案 0 :(得分:1)

将其包含在隐式游标for for循环中的BEGIN..END块中。

DO $$ 
    BEGIN
    for rec IN ( select code, group_id FROM my_table ) 
    LOOP
      BEGIN
        UPDATE my_table SET code = REPLACE(code, 'abd', 'abc') WHERE code=rec.code AND group_id=rec.group_id;
      EXCEPTION
        WHEN unique_violation THEN
            DELETE FROM my_table WHERE code = 'abd' AND group_id = ?;
      END;
    END LOOP;
END $$;