我想将数据导入到我的 postgresql 表中。 我有格式如下的 .csv 文件:
1; John Blake
2; Roberto Young
3;Mark Palmer
有什么解决方案可以去除第一个空白吗?
我使用了以下代码
\copy users from 'users.csv' using delimiters E';'
它确实保留了空格
最佳答案
COPY
到临时暂存表,然后从那里 INSERT
到目标表,修剪文本列。
CREATE TEMP TABLE tmp_x AS
SELECT * FROM users LIMIT 0; -- empty temp table with structure of target
\copy tmp_x FROM '/absolute/path/to/file' delimiters E';'; -- psql command (!)
INSERT INTO users
(usr_id, usr, ...) -- list columns
SELECT usr_id, ltrim(usr), ...
FROM tmp_x;
DROP TABLE tmp_x; -- optional; is destroyed at end of session automatically
ltrim()
仅修剪字符串左侧的空格。
这一系列操作的执行效果比 COPY
之后更新表中的行要好,后者需要更长的时间并会产生死行。此外,只有新导入的行才会以这种方式进行操作。
相关答案:
Delete rows of a table specified in a text file in Postgres
关于sql - 导入 csv 数据时去除第一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23527974/