我有一个触发器函数,可以在更新时将唯一值的行复制到另一个表,或插入ALMOST工作。
触发器只应在示例表中插入新行(如果之前不存在该数字)。自动取款机。如果表中已存在数字,它会向样本表中插入一个值为NULL的新行。如果maintbl.number = sample.nb_main
,我不希望它做任何事情编辑:样本表和样本数据
CREATE TABLE schema.main(
sid SERIAL NOT NULL,
number INTEGER,
CONSTRAINT sid_pk PRIMARY KEY (sid)
)
CREATE TABLE schema.sample(
gid SERIAL NOT NULL,
nb_main INTEGER,
CONSTRAINT gid_pk PRIMARY KEY (gid)
示例和期望的结果
schema.main schema.sample number nb_main 234233 234233 234234 555555 234234 555555 555555
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
INSERT INTO schema.sample(
nb_main)
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION schema.update_number()
OWNER TO postgres;
CREATE TRIGGER update_number
AFTER INSERT OR UPDATE
ON schema.maintbl
FOR EACH ROW
EXECUTE PROCEDURE schema.update_number();
我刚刚发现我的选择查询可能是错误的,如果我自己运行SELECT查询它返回一行'NULL'但我不应该?
SELECT DISTINCT(maintbl.number)
FROM schema.maintbl
WHERE NOT EXISTS (
SELECT nb_main FROM schema.sample WHERE maintbl.number = sample.nb_main);
有什么好建议吗? 最好
答案 0 :(得分:0)
如果我理解正确,您希望在schema.sample
附加schema.maintbl
已插入或更新的号码,对吧?
CREATE OR REPLACE FUNCTION schema.update_number()
RETURNS trigger AS
$BODY$
BEGIN
IF (SELECT COUNT(*) FROM schema.sample WHERE number = NEW.number) = 0 THEN
INSERT INTO schema.sample(nb_main) VALUES (NEW.number);
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;