我在触发器中有递归问题。
我有桌子:
CREATE TABLE employees(
task int4 NOT NULL,
first_name varchar(40) NOT NULL,
last_name varchar(40) NOT NULL,
PRIMARY KEY (task, cli_id_number)
);
当我插入值时:
(123, name, last)
我想自动插入这些值:
(321, name, last)
我是按照以下方式执行此操作,但显然触发器是递归的,并且在第一次递归后它尝试插入先前插入的值。
CREATE OR REPLACE FUNCTION insert_task() RETURNS trigger AS $BODY$
BEGIN
IF new.task = '123' AND (
SELECT cant FROM (
SELECT name, task, count(*) AS cant
FROM client_task
WHERE name = NEW.name AND task = NEW.task
GOUP BY 1,2
HAVING count(*) <= 1
) t) = 1 THEN
INSERT INTO client_task(task, name, last_name)
VALUES('321', NEW.task, NEW.name, NEW.last_name);
RETURN NEW;
ELSE
IF NEW.task = '321' AND (
SELECT cant FROM (
SELECT name, task, count(*) AS cant
FROM client_task
WHERE name = NEW.name AND task = NEW.task
GROUP BY 1, 2
HAVING count(*) <=1
) t) = 1 THEN
INSERT INTO client_task(task, name, last_name)
VALUES('123', NEW.task, NEW.name, NEW.last_name);
RETURN NEW;
END IF;
END IF;
RETURN NULL;
END; $BODY$ LANGUAGE 'plpgsql';
任何帮助表示感谢。
答案 0 :(得分:0)
使用pg_trigger_depth()
函数返回(as stated in the documentation):
PostgreSQL触发器的当前嵌套级别(如果未调用则为0, 直接或间接地从触发器内部开始)
CREATE TRIGGER insert_task
AFTER INSERT ON employees
FOR EACH ROW
WHEN (pg_trigger_depth() = 0)
EXECUTE PROCEDURE insert_task()