对 postgres 中的唯一违规执行删除或更新
在 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;
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 update the is_dup=true to that row
end;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION rem_chars() OWNER TO postgres;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
-- 这将向您显示所有潜在的按键冲突
-- 这将删除它们
-- this will show you all the potential key collisions
-- this will delete them
我认为唯一的解决方案是分两步完成:
至少我想不出更有效的方法。
I think the only solution is to do this in two steps:
At least I can't think of a more efficient way.