Run SQL statements in PL/pgSQL only if a row doesn't exist

前端 未结 4 671
说谎
说谎 2020-12-21 18:26

I want to do something like this in a PL/pgSQL function in Postgres 9.6:

INSERT INTO table1 (id, value) VALUES (1, \'a\') ON CONFLICT DO NOTHING;
--- If the          


        
4条回答
  •  执笔经年
    2020-12-21 19:21

    Maybe you mean something like this?

    INSERT INTO table1 (id, value) VALUES (1, 'a') ON CONFLICT DO NOTHING;
    --- If the above statement didn't insert a new row
    ---   because id of 1 already existed, 
    ---   then run the following statements
    
    affected_rows := SQL%ROWCOUNT;
    
    IF affected_rows = 0 THEN
        INSERT INTO table2 (table1_id, value) VALUES (1, 'a');
        UPDATE table3 set (table1_id, time) = (1, now());
    END IF
    

提交回复
热议问题