1

我有一个表“消息”。对于每个插入的行,我必须在同一个表“消息”中插入该行的多个副本(用于大量邮寄)。我为它做了一个触发器(例如一个副本)。

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)?谢谢

4

1 回答 1

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;

=> sql 小提琴演示

于 2013-09-02T07:39:18.027 回答