我有一张表“消息”。对于每个INSERT的行,我必须在同一个表“messages”中插入该行的几个副本(用于群发邮件)。我为它做了一个触发器(例如一个副本)。
CREATE OR REPLACE FUNCTION some_trigger()
RETURNS trigger AS
$BODY$
DECLARE
BEGIN
INSERT INTO messages (some_field) VALUES (NEW.some_value_copy)
RETURN NEW;
END
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER some_tg BEFORE INSERT ON messages FOR EACH ROW EXECUTE PROCEDURE some_trigger();
我如何将NEW扩展为
INSERT INTO messages (some_field) VALUES (NEW.some_value),(NEW.some_value_copy)
?
THX
答案 0 :(得分:1)
仍然不知道你的架构,所以很难提供帮助,但我认为你可以做一些接近这个的事情:
CREATE OR REPLACE FUNCTION ins_messages()
RETURNS trigger AS
$BODY$
DECLARE
BEGIN
if NEW.usr is not null then
return NEW; -- making actual insert
end if;
if NEW.sender <> '-1' then
insert into messages (message, usr, sender, receiver)
values
(NEW.message, NEW.sender, NEW.sender, NEW.receiver),
(NEW.message, NEW.receiver, NEW.sender, NEW.receiver);
else
insert into messages (message, usr, sender, receiver)
select NEW.message, name, NEW.sender, name
from users;
end if;
return null;
END;
$BODY$
LANGUAGE plpgsql;