Postgresql,检查插入时触发错误

Postgresql,检查插入时触发错误,postgresql,triggers,Postgresql,Triggers,当我在我的historial表中插入数据时,我试图使用触发器进行检查,如果historial表的某一行与我要插入的数据具有相同的IDU,我需要在插入之前进行检查。我已经使用了这个触发器和这个函数,但是我不能让它工作 这是我的触发器: CREATE TRIGGER VerificarInsercion BEFORE INSERT ON public."Historial" FOR EACH ROW EXECUTE PROCEDURE VerificarHistorial(); 我已经尝试删除每

当我在我的historial表中插入数据时,我试图使用触发器进行检查,如果historial表的某一行与我要插入的数据具有相同的IDU,我需要在插入之前进行检查。我已经使用了这个触发器和这个函数,但是我不能让它工作

这是我的触发器:

CREATE TRIGGER VerificarInsercion
BEFORE INSERT ON public."Historial"
FOR EACH ROW 
EXECUTE PROCEDURE VerificarHistorial();
我已经尝试删除每一行,因为我想要的是只运行一次,而不是每一行

最后,我的功能验证历史:

BEGIN
  IF (SELECT Count (*) FROM public."Historial" WHERE estado = 1 AND "IDU" = NEW."IDU") < 1 THEN 
      INSERT INTO public."Historial" (usuario, vehiculo, mercancia, "combustibleInicial", ruta, "horaSalida", estado, "IDU", fecha)
      VALUES (NEW.usuario, NEW.vehiculo, NEW.mercancia, NEW."combustibleInicial", NEW.ruta, NEW."horaSalida", NEW.estado, NEW."IDU", NEW.fecha);
  END IF;
  RETURN null;
END;
我得到这个错误:

ERROR:  stack depth limit exceeded
HINT:  Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
CONTEXT:  SQL statement "SELECT (SELECT Count (*) FROM public."Historial" WHERE estado = 1 AND "IDU" = NEW."IDU") < 1"
PL/pgSQL function verificarhistorial() line 2 at IF
SQL statement "INSERT INTO public."Historial" (usuario, vehiculo, mercancia, "combustibleInicial", ruta, "horaSalida", estado, "IDU", fecha)
      VALUES (NEW.usuario, NEW.vehiculo, NEW.mercancia, NEW."combustibleInicial", NEW.ruta, NEW."horaSalida", NEW.estado, NEW."IDU", NEW.fecha)"
PL/pgSQL function verificarhistorial() line 3 at SQL statement
我检查了其他类似的回答,没有结果


是否可以制作一个函数来检查是否有任何行具有与插入数据相同的IDU?

每次向表中插入新行时都会调用触发器函数。如果您试图在函数中插入一行,则会再次调用该函数,依此类推。这样可以实现堆栈溢出

不要尝试在插入时调用的触发器函数中插入行

BEGIN
    IF EXISTS (SELECT 1 FROM "Historial" WHERE estado = 1 AND "IDU" = NEW."IDU") THEN 
        RETURN null;
    END IF;
    RETURN new;
END; $$;
事实上,如果创建部分唯一索引,则不需要触发器:

create unique index on "Historial" ("IDU") where estado = 1

您不应该在触发器中插入新行,这会导致无限递归。我认为可以通过创建这样一个独特的索引来实现:

set search_path = public;
create unique index on "Historial" ("IDU") where estado = 1;
相同的问题,但有关Stackoverflow中已回答的更新命令,请参阅以下链接:


您不需要触发器,只需在该字段上创建一个唯一的索引即可。无法对正在创建触发器的表进行选择。是的,但是,IDU可以在表上重复,只有一行可以具有estado==1和相同的IDU,但其他行可以具有相同的IDU,但estado==0。您需要创建一个后插入触发器。后插入?我试图阻止使用相同的IDU和estado==1再插入20行,应该在前面,不是吗?
set search_path = public;
create unique index on "Historial" ("IDU") where estado = 1;