【发布时间】:2017-04-05 00:25:37
【问题描述】:
我在尝试执行触发器时遇到了麻烦。假设我们有 2 个表,我想将数据从 表 A 复制到 表 B,但每个表都有一个唯一约束。
create table test1 (
test_name varchar);
create unique index test1_uc on test1 USING btree (test_name);
create table test2 (
test_name2 varchar);
create unique index test2_uc on test2 USING btree (test_name2);
CREATE OR REPLACE FUNCTION trig_test()
RETURNS trigger AS
$$
BEGIN
IF pg_trigger_depth() <> 1 THEN
RETURN NEW;
END IF;
INSERT INTO test2(test_name2)
VALUES(NEW.test_name2)
ON CONFLICT (test_name2) DO NOTHING;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trigger_test
AFTER INSERT
ON test2
FOR EACH ROW
EXECUTE PROCEDURE trig_test();
insert into test2 values ('test');
insert into test2 values ('test'); //should do nothing ?
但我收到此错误:
ERROR: duplicate key value violates unique constraint "test2_uc" DETAIL: Key (test_name2)=(test) already exists.
触发器有什么问题?
【问题讨论】:
-
您需要在触发器中使用
return null。并且触发器必须是BEFORE触发器 -
触发器之前很好,但如果我返回 null 我不能从表 1 复制到表 2 cf rextester.com/LAJB87421
标签: postgresql triggers duplicates plpgsql upsert