PostgreSQL COPY 命令中动态生成的表名
这个 PostgreSQL COPY 命令有效:
copy tablename from E'c:\\abc\\a.txt';
但我希望动态生成表名。我该怎么做?
This PostgreSQL COPY command works:
copy tablename from E'c:\\abc\\a.txt';
but I want the tablename to be dynamically generated. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要构建一个字符串,连接动态表名称,然后使用execute。请注意,您对 ' by '' 进行了转义。这还包括保存文件的动态名称。您需要将 savedir 替换为您正在使用的实际目录。
编辑:
自从我第一次写这篇文章以来,我发现了格式函数,我认为它通常比使用连接运算符 || 生成的 SQL 更容易阅读。并且更加灵活。
有关完整讨论,请参阅官方文档: https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN
You need to build a string, concatenating in the dynamic table name, and then use execute. Note that you escape the ' by ''. This also includes a dynamic name to save the file too. You need to replace savedir with the actual directory you are using.
EDIT:
Since I first wrote this, I have discovered the format function, which I think is generally easier to read than SQL generated with the concatenation operator || and more flexible.
See the official docs for a full discussion: https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN
您可以通过 shell 脚本将多个 csv 文件复制到表中。
制作脚本文件:
vim csvtotable
编写csvtotable脚本。这是我的例子:
#!/bin/sh DBNAME=postgres files=$1 表示 ${files} 中的文件;执行 psql -d ${DBNAME} -c "\copy Parent_tree(parent_id, some_text) FROM '${file}' 分隔符 ',' csv header" 完成
执行脚本。
./csv2table“$(ls *.out.csv)”
显然,本地 CSV 文件应该与表匹配。然后,如果 csv 文件名以 .out.csv 结尾,它将从 csv 导入到数据库表。
我不确定 csv 名称匹配是全局匹配还是仅当前目录匹配。
参考链接:
-c
命令参考 https ://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-PATTERNSchomd 命令: https://linuxize.com/post/chmod-command-in- linux/
bash shanebang: https://linuxize.com/post/bash-shebang/
You can copy from multi csv files to an table via shell script.
Make an script file:
vim csvtotable
write csvtotable script. Here is my example:
#!/bin/sh DBNAME=postgres files=$1 for file in ${files}; do psql -d ${DBNAME} -c "\copy parent_tree(parent_id, some_text) FROM '${file}' delimiters ',' csv header" done
Execute the script.
./csv2table "$(ls *.out.csv)"
Obviously, Local CSV file should be match with table. Then It will import from csv to database tables if csv file name ending with .out.csv.
I am not sure csv name match is global or just at present directory match.
Reference link:
-c
command reference https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-PATTERNSchomd command: https://linuxize.com/post/chmod-command-in-linux/
bash shanebang: https://linuxize.com/post/bash-shebang/