Postgres Insert Into View Rule with Returning Clause

后端 未结 1 1315
孤街浪徒
孤街浪徒 2021-01-12 12:32

I am attempting to allow insert statements with a returning clause into a view in Postgres v9.4, but am struggling with the syntax. This is how I want to call the insert st

相关标签:
1条回答
  • 2021-01-12 13:09

    You are much better off using an INSTEAD OF INSERT trigger here:

    CREATE FUNCTION MyFuncName() RETURNS trigger AS $$
    DECLARE
      id integer;
    BEGIN
      INSERT INTO tableA (time) VALUES COALESCE(NEW.time, NOW()) RETURNING aPrimaryKey INTO id;
      INSERT INTO tableB (aPrimaryKey, someCol1) VALUES (id, NEW.someValue);
      RETURN NEW;
    END; $$ LANGUAGE PLPGSQL;
    
    CREATE TRIGGER MyView_on_insert INSTEAD OF INSERT ON MyView
      FOR EACH ROW EXECUTE PROCEDURE MyFuncName();
    

    Checking the current value of a sequence to see what was inserted in another table is bad bad bad practice. Even while you are here in a single transaction, don't do it.

    You are confused about the issue of RETURNING information, because I am confused too when I read your question. Inside of a function use the INTO clause to populate locally declared variables to hold record values which you can then use in subsequent statements. Outside of a function, use the RETURNING clause as you do in your top-most code snippet.

    0 讨论(0)
提交回复
热议问题