对postgres中的唯一违规执行删除或更新

问题描述 投票:0回答:2

在Unique_violation异常上如何更新或删除引发异常的行

表格代码和插入

create table test
(
id serial not null,
str character varying NOT NULL,
is_dup boolean DEFAULT false,
CONSTRAINT test_str_unq UNIQUE (str)
);

INSERT INTO test(str) VALUES ('apple'),('giant'),('company'),('ap*p*le');

功能

CREATE OR REPLACE FUNCTION rem_chars()
  RETURNS void AS
$BODY$

BEGIN
begin 
update test set str=replace(str,'*','');
EXCEPTION WHEN unique_violation THEN
--what to do here to delete the row which raised exception or
--to update the is_dup=true to that row 
end;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION rem_chars() OWNER TO postgres;
postgresql unique sql-delete unique-constraint
2个回答
2
投票

- 这将显示所有潜在的关键碰撞

SELECT a.id, a.str, b.id , b.str
FROM test a, test b
WHERE a.str = replace(b.str,'*','')
AND a.id < b.id;

- 这将删除它们

DELETE FROM test WHERE id IN (
  SELECT b.id
  FROM test a, test b
  WHERE a.str = replace(b.str,'*','')
  AND a.id < b.id
);

0
投票

我认为唯一的解决方案是分两步完成:

UPDATE test 
  SET str = replace(str,'*','')
  WHERE str NOT IN (SELECT replace(str,'*','') FROM test);

UPDATE test
  SET is_dup = true
  WHERE str IN (SELECT replace(str,'*','') FROM test);

至少我想不出更有效的方法。

© www.soinside.com 2019 - 2024. All rights reserved.