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

发布于 2024-10-11 00:06:26 字数 719 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅语花开 2024-10-18 00:06:26

-- 这将向您显示所有潜在的按键冲突

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

-- 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
);
往日情怀 2024-10-18 00:06:26

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文