Postgresql触发器函数似乎阻止插入任何记录

Postgresql触发器函数似乎阻止插入任何记录,sql,function,postgresql,triggers,Sql,Function,Postgresql,Triggers,我是Postgresql的新手 我创建了一个函数来检查INSERT是否试图在两个不同的表中创建相同的值 CREATE OR REPLACE FUNCTION check_pids_not_equal() RETURNS trigger AS $BODY$ begin if exists (select * from cards c , echecks e where c.pid = e.pid) then raise NOTICE 'Must have different PID

我是Postgresql的新手

我创建了一个函数来检查INSERT是否试图在两个不同的表中创建相同的值

    CREATE OR REPLACE FUNCTION check_pids_not_equal()
  RETURNS trigger AS
$BODY$
begin 
if exists (select *
from cards c , echecks e
where c.pid = e.pid)
then
raise NOTICE 'Must have different PID than entry in cards.pid';
end if;
return null;
end
$BODY$
  LANGUAGE plpgsql
我以这种方式分配触发器:

CREATE TRIGGER check_cards_pids_trigger
  BEFORE INSERT OR UPDATE
  ON cards
  FOR EACH ROW
  EXECUTE PROCEDURE check_pids_not_equal();
现在,每当我尝试在Cards表上插入任何记录时,我总是得到
insert 0 0
,并且没有错误消息——即使该记录显然是一条缺少列或列类型错误的坏记录


对罪犯有什么看法?另外,如何显示更多错误报告?

如果要插入记录,必须
返回新记录,如下所示:

CREATE OR REPLACE FUNCTION check_pids_not_equal()
  RETURNS trigger AS
$BODY$
begin 
    if exists (select * from cards c, echecks e where c.pid = e.pid) then
        raise NOTICE 'Must have different PID than entry in cards.pid';
        return null;
    end if;
    return new;
end
$BODY$
LANGUAGE plpgsql

这修复了INSERT的问题(我可以插入记录),但当我将一个pid插入表Echecks中,该pid已经存在于卡片pid中,插入仍然完成,即触发器没有阻止插入并根据需要发出通知。不知道您
存在
检查应该做什么。无论如何,您可以使用
new.pid
获取当前插入记录的
pid
。谢谢。我需要使用new.pid关键字。我试图使用cards.pid作为参考,但您的评论使我意识到触发器在插入之前可以工作。因此,cards.pid还不在引用表中。非常感谢。