Im trying to use a trigger to check when I insert a data on my table "historial", I need to check before to insert, if some row of the table "Historial" has the same IDU as the data that I'm insert. I have use this trigger and this function, but I can't make it work..
That its my trigger:
CREATE TRIGGER VerificarInsercion
BEFORE INSERT ON public."Historial"
FOR EACH ROW
EXECUTE PROCEDURE VerificarHistorial();
(I've tried removing "FOR EACH ROW", since what I want is to run only once and not for each row)
And finally, my function 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;
When I insert some data in "Historial":
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')
I get this error:
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
I have checked other similar responses, without result.
Some idea to make a function that check if any row have the same IDU that the insert data?