开发者

perform delete or update on unique violation in postgres

On Unique_violation exception how to update or delete the row which raised the exception

table code and insert

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');

Function

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 u开发者_如何学JAVApdate the is_dup=true to that row 
end;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION rem_chars() OWNER TO postgres;


-- this will show you all the potential key collisions

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;

-- this will delete them

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
);


I think the only solution is to do this in two steps:

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);

At least I can't think of a more efficient way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜