Database: PostgreSQL
I need function in PL/pgSQL to load data into a table from CSV file automatically. Important: columns of CSV file and columns of a target table must declared.
some_function(data_file_name, table_name, columns_from, columns_to)
EXAMPLE:
CSV file has columns: A, B, C, D
target table has columns: one, two
some_function('file.csv', 'table1', array['A', 'B'], array['one', 'two'])
Array definition can be changed, I don't know how to pass columns if the other way.
create or replace function load_csv_procedure
(
csv_path text,
target_table text,
columns_from text[],
columns_to text[]
)
returns void as $$
declare
target_table text;
col_count integer;
iter integer;
col text;
col_first text;
begin
set schema 'public';
create table temp_table ();
col_count := 6;
-- add just enough number of columns
for iter in 1..col_count
loop
execute format('alter table temp_table add column col_%s text;',
iter);
end loop;
-- copy the data from csv file
execute format('copy temp_table from %L with delimiter '','' quote
''"'' csv ', csv_path);
iter := 1;
col_first := (select col_1 from temp_table limit 1);
for col in execute format('select
unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from
temp_table where col_1 = %L', col_first)
loop
execute format('alter table temp_table rename column col_%s to
%s', iter, col);
iter := iter + 1;
end loop;
execute format('delete from temp_table where %s = %L', col_first,
col_first);
--EXECUTE format('INSERT INTO %I (' || columns_to::text || ' ) VALUES
( select (' || columns_from::text || ' ) from temp_table);'::text,
target_table) using columns_to, columns_from;
--
EXECUTE format('INSERT INTO %I (''name'', code ) VALUES (select
DepartmentName, DepartmentCode from temp_table);'::text,
target_table); -- using columns_to, columns_from;
drop table temp_table;
end;
$$ language plpgsql;
CREATE TEMP TABLE temp_table () ON COMMIT DROP;this will make it local to the session and it will garantee cleanup at end of transaction.