我想在插入之前创建一个触发器,并在触发器函数内部检查要插入的新行的summary_id值,以查看表中是否已存在summary_id。如果它存在,则触发器应返回null,因为我不想插入重复值。我已经编写了这个函数,但是,当我尝试添加一个新的重复行时,它已成功插入!
CREATE OR REPLACE FUNCTION trigger_ack_bi()
RETURNS trigger AS $$
--DECLARE
-- max_points INTEGER;
BEGIN
IF(TG_OP = 'INSERT') THEN
IF NEW.ack_summary_id = (SELECT ack_summary_id FROM scm_main.tbl_ack WHERE scm_main.tbl_ack.ack_summary_id = NEW.ack_summary_id LIMIT 1) THEN
RETURN NULL;
ELSE
RETURN NEW;
END IF;
END IF;
END;
$$LANGUAGE plpgsql;
CREATE TRIGGER trigger_ack_bi BEFORE INSERT ON
scm_main.tbl_ack
FOR EACH ROW
EXECUTE PROCEDURE trigger_ack_bi()
ALTER FUNCTION trigger_ack_bi() OWNER TO postgres;
答案 0 :(得分:0)
我建议将列设置为NOT NULL并在其上创建PK ...
alter table scm_main.tbl_ack alter column ack_summary_id set NOT NULL;
alter table scm_main.tbl_ack add primary key (ack_summary_id);
答案 1 :(得分:0)
似乎触发功能是正确的。但是,它以静默模式运行。提出异常是我需要确保防止重复的原因。感谢您提供其他解决方案。
CREATE OR REPLACE FUNCTION trigger_ack_bi()
RETURNS trigger AS $$
--DECLARE
-- max_points INTEGER;
BEGIN
IF(TG_OP = 'INSERT') THEN
IF NEW.ack_summary_id IS NULL THEN
RAISE EXCEPTION 'summaryID cannot be null';
END IF;
IF NEW.ack_summary_id = (SELECT ack_summary_id FROM scm_main.tbl_ack WHERE scm_main.tbl_ack.ack_summary_id = NEW.ack_summary_id LIMIT 1) THEN
RAISE EXCEPTION 'duplication prevented..';
RETURN NULL;
ELSE
RETURN NEW;
END IF;
END IF;
END;
$$LANGUAGE plpgsql;
CREATE TRIGGER trigger_ack_bi BEFORE INSERT ON
scm_main.tbl_ack
FOR EACH ROW
EXECUTE PROCEDURE trigger_ack_bi()