[英]When using psql to copy from a csv file, a “” for a null column generates an error instead of a null
I'm trying to use copy to copy a large csv file into a postgres table.我正在尝试使用 copy 将大型 csv 文件复制到 postgres 表中。
A certain integer column is primarily null.某integer列主要是null。 In the csv file, this column just has "".在 csv 文件中,这一列只有“”。
Every column is quoted, which doesn't seem to be an issue for other columns.每一列都被引用,这对于其他列似乎不是问题。
I get this error when I try to copy it:当我尝试复制它时出现此错误:
ERROR: invalid input syntax for integer: ""
I tried setting a NULL clause to '' and "" in my copy statement.我尝试在我的复制语句中将 NULL 子句设置为“”和“”。 '' does nothing, "" generates an error: '' 什么都不做,"" 生成错误:
zero-length delimited identifier at or near """"
I tried using sed to change all "" to " ", but that still doesn't work even when I set the null clause to " ".我尝试使用 sed 将所有“”更改为“”,但即使将 null 子句设置为“”,这仍然不起作用。 I still get我仍然得到
ERROR: invalid input syntax for integer: " "
For now I am able to proceed by sed'ing the column to -1.现在,我可以通过将列设置为 -1 来继续。 I don't really care about this column much anyways.反正我不是很关心这个专栏。 I'd be ok to just setting it to null, or ignoring it, but when I tried to take it out of the column definition section of the copy command, postgres yelled at me.我可以将它设置为 null,或者忽略它,但是当我试图将它从复制命令的列定义部分中取出时,postgres 对我大喊大叫。
So my question comes down to this: how can I tell postgres to treat "" as a null value?所以我的问题归结为:如何告诉 postgres 将 "" 视为 null 值?
Thank you.谢谢你。
The typical way to indicate a missing value (null) in a.csv file is to just put nothing into that field.在 a.csv 文件中指示缺失值 (null) 的典型方法是在该字段中不添加任何内容。 For instance, if you have three columns ( A
, B
and C
) and there is no value for B
, the.csv file would contain "Col A value",,"Col C value"
.例如,如果您有三列( A
、 B
和C
)并且B
没有值,则 .csv 文件将包含"Col A value",,"Col C value"
""
is a string value, not a numeric value, so there's no way for it to be considered one. ""
是一个字符串值,而不是一个数值,因此无法将其视为一个值。
This is what the force_null
option is for:这就是force_null
选项的用途:
Match the specified columns' values against the null string, even if it has been quoted将指定列的值与 null 字符串匹配,即使它已被引用
So assuming the name of the int column is "y":所以假设 int 列的名称是“y”:
\copy foo from foo.csv with (format csv, force_null (y));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.