Continuing a transaction after primary key violation error

前端 未结 4 1053
旧巷少年郎
旧巷少年郎 2020-11-30 07:56

I am doing a bulk insert of records into a database from a log file. Occasionally (~1 row out of every thousand) one of the rows violates the primary key and causes the tran

4条回答
  •  天涯浪人
    2020-11-30 08:38

    I would use a stored procedure to catch the exceptions on your unique violations. Example:

    CREATE OR REPLACE FUNCTION my_insert(i_foo text, i_bar text)
      RETURNS boolean LANGUAGE plpgsql AS
    $BODY$
    begin   
        insert into foo(x, y) values(i_foo, i_bar);
        exception
            when unique_violation THEN -- nothing
    
        return true;
    end;
    $BODY$;
    
    SELECT my_insert('value 1','another value');
    

提交回复
热议问题