当我在“historial”表中插入数据时,我试图使用触发器进行检查,如果“historial”表中的某些行与我要插入的数据具有相同的IDU,则需要在插入之前进行检查。我已经使用了这个触发器和这个函数,但是我不能让它工作。。
postgresql - PostgreSQL,在检查插入时触发错误-LMLPHP
这是我的导火索:

CREATE TRIGGER VerificarInsercion
BEFORE INSERT ON public."Historial"
FOR EACH ROW
EXECUTE PROCEDURE VerificarHistorial();

(我试过删除“每行”,因为我只想运行一次,而不是每行)
最后,我的函数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;

当我在“历史”中插入一些数据时:
INSERT INTO public."Historial" (usuario, vehiculo, mercancia, "combustibleInicial", ruta, "horaSalida", estado, "IDU", fecha) VALUES ('David', '3424SDA', 200, 50, 'Cáceres-Sevilla', 'dom, 3 sep, 05:20 PM', 1, 50, '2017-09-03T15:21:07.442Z')

我得到这个错误:
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与insert数据相同?

最佳答案

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

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

关于postgresql - PostgreSQL,在检查插入时触发错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46025559/

10-14 13:40
查看更多