Postgresql:将一些正确的默认值或 NA 插入到 table 中,并且输入错误的值?

Postgresql: inserting some proper default values or NAs into table with maltyped values?

我有一个带有浮动列的 table。我想在其中插入一个 malformatted/maltyped CSV,以便我将所有值都转换为浮点数,并且所有格式错误的值都会触发错误,并将获得零值。在伪代码中,我正在寻找 iserror(cast(newValue as float),0).

小实例

CSV 看起来像这样

Ex1,Ex2,Ex3
1,2,hhh
1.2,1.0,1.9
a,2,3

和 table 干净复制的创作

CREATE TABLE example
(
"Ex1" float,
"Ex2" float,
"Ex3" float
);

/*Copy with clean data*/
COPY example FROM '/tmp/test.csv' WITH CSV HEADER DELIMITER ',';

最后一条命令会引发错误,因为我们无法将非浮点值插入 table。

Error trapping 可能有助于解决我的问题,但我不确定如何将其与 CSV

的插入一起使用
[ <<label>> ]
[ DECLARE
    declarations ]
BEGIN
    statements
EXCEPTION
    WHEN condition [ OR condition ... ] THEN
        handler_statements
    [ WHEN condition [ OR condition ... ] THEN
          handler_statements
      ... ]
END;

问题

How can I insert some proper default values or NAs into table with maltyped values?

该函数在其他情况下也可能有用:

create or replace function to_float(text)
returns float language plpgsql as $$
begin
    return ::float;
exception
    when invalid_text_representation then
        return 0::float;
end $$;

遗憾的是,您不能在 COPY 命令中使用函数。您需要一个缓冲区,即临时 table:

create temp table buffer (ex1 text, ex2 text, ex3 text);
copy buffer from '/tmp/test.csv' with csv header delimiter ',';

insert into example
select to_float(ex1), to_float(ex2), to_float(ex3)
from buffer;

drop table buffer;

最后:

select *
from example;

 Ex1 | Ex2 | Ex3 
-----+-----+-----
   1 |   2 |   0
 1.2 |   1 | 1.9
   0 |   2 |   3
(3 rows)