2011-01-10 41 views
0

在Unique_violation異常是如何更新或刪除其引發的異常進行刪除或Postgres的

表的代碼行和插入獨特的違規行爲更新

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; 
+0

它是什麼,你想做什麼?在異常中刪除或更新? – 2011-01-10 18:38:43

回答

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

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

1

- 這將顯示你所有的潛在鍵衝突

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