1

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

2 に答える 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
);
于 2011-05-10T15:18:12.350 に答える
0

唯一の解決策は、これを2つのステップで行うことだと思います。

更新テスト
  SET str = replace(str,'*','')
  WHERE str NOT IN (SELECT replace(str,'*','') FROM テスト);

更新テスト
  SET is_dup = true
  WHERE str IN (SELECT replace(str,'*','') FROM テスト);

少なくとも私はより効率的な方法を考えることはできません。

于 2011-01-11T15:20:12.227 に答える