Postgres - 用一些文字替换特殊字符#

时间:2017-08-21 08:04:26

标签: postgresql

我有一个从csv文件导入数据的函数 - 这反过来又创建了一个基于csv文件中没有列的表。

有一行代码从csv文件导入列名,然后根据csv文件中的数据将临时列名重命名为实际名称。

create or replace function public.load_csv_file
(
target_table text,
csv_path text,
col_count integer
)

returns void as $$

declare

iter integer; -- dummy integer to iterate columns with
col text; -- variable to keep the column name at each iteration
col_first text; -- first column name, e.g., top left corner on a csv file or     spreadsheet

begin
set schema 'public';

create table insert_from_csv ();

-- add just enough number of columns
for iter in 1..col_count
loop
    execute format('alter table insert_from_csv add column col_%s text;', iter);
end loop;

-- copy the data from csv file
execute format('copy insert_from_csv from %L with delimiter '','' quote ''"'' csv ', csv_path);

iter := 1;
col_first := (select col_1 from insert_from_csv limit 1);

-- update the column names based on the first row which has the column names
for col in execute format('select unnest(string_to_array(lower(replace(trim(insert_from_csv::text, ''()''),'' '',''_'')), '','')) from insert_from_csv where col_1 = %L', col_first)
loop
    execute format('alter table insert_from_csv rename column col_%s to %s', iter, col);
    iter := iter + 1;
end loop;

-- delete the columns row
execute format('delete from insert_from_csv where %s = %L', col_first, col_first);

-- change the temp table name to the name given as parameter, if not blank
if length(target_table) > 0 then
    execute format('alter table insert_from_csv rename to %I', target_table);
end if;

end;

$$ language plpgsql;

在第一个语句中,我使用'replace'来删除'_'中的空格,但是当我尝试为'#'做同样的事情时,在postgres中获取错误-b'ze#指的是注释。

有没有人知道用'some text'替换'#'的方法。

参考功能:

date    Metrics # of Applications
01-Apr-17       95
02-Apr-17       122
03-Apr-17       110
04-Apr-17       94
05-Apr-17       122
06-Apr-17       93
07-Apr-17       97

CSV数据:

{{1}}

由于

0 个答案:

没有答案