如何在将批处理插入表中的同时提交循环中的每个迭代

问题描述

我写了一个存储过程,从一个大表中选择记录块,然后分批插入到另一个表中。似乎并不是每次迭代都插入记录,而是在最后一次全部插入所有批次。有没有一种方法可以在每次迭代中将记录实际插入到目标表中?

这就是我的功能

CREATE OR REPLACE FUNCTION cms.load_records_from_staging_batch(batch_size int)
  RETURNS void
  LANGUAGE plpgsql
AS
$body$
DECLARE 
  row_cnt int;
  oset int;
  counter int;
BEGIN
  row_cnt := (select count(*)::int from cost_settlements_stg);
  raise notice 'Total % rows in cost_settlements_stg',row_cnt;
  oset := 0;
  while oset <= row_cnt loop
    insert into cms.cost_settlements 
      (item_text,item_description)
      select item_text,item_description
      from cms.cost_settlements_stg limit batch_size offset oset
    on conflict on constraint cost_settlements_unique_key 
    do nothing;
    
    oset := oset + batch_size;
    counter := counter + 1;
    raise notice 'Batch loaded %',counter';
  end loop;
END;

解决方法

行将随行插入,只是直到事务结束前它们才是不可见的。

在单个事务和单个语句中完成所有插入操作,这将很快:

INSERT INTO cms.cost_settlements (item_text,item_description)
SELECT item_text,item_description
FROM cms.cost_settlements_stg
ON CONFLICT ON CONSTRAINT cost_settlements_unique_key DO NOTHING;