Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql:在具有错误类型值的表中插入一些适当的默认值或NAs?_Postgresql_Csv_Error Handling_Plpgsql - Fatal编程技术网

Postgresql:在具有错误类型值的表中插入一些适当的默认值或NAs?

Postgresql:在具有错误类型值的表中插入一些适当的默认值或NAs?,postgresql,csv,error-handling,plpgsql,Postgresql,Csv,Error Handling,Plpgsql,我有一个带有浮动列的表。我想在其中插入一个格式错误/类型错误的CSV,这样我可以将所有值转换为float,所有格式错误的值触发一个错误,将得到一个零值。在speudo代码中,我正在寻找iserror(cast(newValue作为float),0) 小型工作示例 CSV看起来像这样 Ex1,Ex2,Ex3 1,2,hhh 1.2,1.0,1.9 a,2,3 以及使用干净的复制创建表 CREATE TABLE example ( "Ex1" float, "Ex2" float, "Ex3" f

我有一个带有浮动列的表。我想在其中插入一个格式错误/类型错误的CSV,这样我可以将所有值转换为float,所有格式错误的值触发一个错误,将得到一个零值。在speudo代码中,我正在寻找iserror(cast(newValue作为float),0)

小型工作示例

CSV看起来像这样

Ex1,Ex2,Ex3
1,2,hhh
1.2,1.0,1.9
a,2,3
以及使用干净的复制创建表

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

/*Copy with clean data*/
COPY example FROM '/tmp/test.csv' WITH CSV HEADER DELIMITER ',';
其中,最后一个命令将引发错误,因为我们无法将非浮点值插入表中

可能有助于解决我的问题,但我不确定如何使用它从CSV插入

[ <<label>> ]
[ DECLARE
    declarations ]
BEGIN
    statements
EXCEPTION
    WHEN condition [ OR condition ... ] THEN
        handler_statements
    [ WHEN condition [ OR condition ... ] THEN
          handler_statements
      ... ]
END;
[]
[宣布
声明]
开始
声明
例外情况
当条件[或条件…]出现时
handler\u语句
[当条件[或条件…]然后
handler\u语句
... ]
结束;
问题 如何将一些适当的默认值或NAs插入到具有错误类型值的表中


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

create or replace function to_float(text)
returns float language plpgsql as $$
begin
    return $1::float;
exception
    when invalid_text_representation then
        return 0::float;
end $$;
不幸的是,您不能在COPY命令中使用函数。您需要一个缓冲区,即临时表:

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)    

创建一个函数也许这会有所帮助