首页 > 解决方案 > 长时间运行的 PostgreSQL 函数返回错误

问题描述

我有一个运行时间很长的函数,需要30 多分钟才能完成。它有一个嵌套循环,一次将大约4800 万条线索以 10.000 条的形式插入到一个表中。如果我传递一个小数据集,那么它会成功运行,并给我插入多少潜在客户的正确响应。但是如果数据集很大,即使完成任务也不会给出任何响应。

在此处输入图像描述

这里有什么问题?

这是我的功能代码。

CREATE OR REPLACE FUNCTION admin.insert_data_into_table(customer_column_names text[], customer_column_ids int[] , schema_name text, dyn_table_name text, bucket_id int, partial_query text)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare
    n INTEGER := 0;
    offset_counter INTEGER := 0;
    i integer;
    chunk_size integer := 10000;
begin
    EXECUTE format('set search_path to %I', schema_name);
    EXECUTE format('SELECT count(*) FROM %I.%I', schema_name, dyn_table_name) into n;
    for i in 1..array_upper(customer_column_ids, 1)
    loop
        offset_counter = 0;
        loop
        EXIT WHEN offset_counter > n; 
            Execute Format('insert into %s.table (customer_id, customer_column_id, value, bucket_id) 
            select _customer_id, %s, %s, %s from %s.%s %s order by _customer_id offset %s limit %s', 
            schema_name, customer_column_ids[i], customer_column_names[i], bucket_id, schema_name, dyn_table_name, partial_query, offset_counter, chunk_size);
            offset_counter := offset_counter + chunk_size; 
        end loop;
    end loop;
    return n;
end;
$function$;

标签: sqlpostgresqlfunctionpollingpgadmin

解决方案


推荐阅读