如何从另一个脚本运行postgresql脚本?

时间:2015-01-14 10:58:19

标签: postgresql

我有一堆SQL脚本在数据库中创建表。每个表都位于一个单独的文件中,因此编辑它们就容易多了。

我想准备一个SQL脚本,它将创建完整的架构,创建表,插入测试数据并为表生成序列。

我能够为oracle数据库做这样的事情,但我遇到了postgres的问题。 问题是 - 我不知道如何从另一个脚本运行表创建脚本。

在oracle中,我使用以下语法执行此操作:

@@'path of the script related to the path of the currently running sql file'

一切都像魅力一样。

在postgres中,我试图寻找类似的东西并发现:

\ir 'relative path to the file'

不幸的是,当我运行我的主脚本时,我收到了消息:

No such file or directory.

示例调用在这里:

\ir './tables/map_user_groups.sql'

我使用Postgres 9.3。我尝试使用psql运行脚本:

psql -U postgres -h localhost -d postgres < "path to my main sql file"

除了调用其他脚本外,文件执行正常。

有人知道如何解决问题吗?

如果问题中的某些内容不清楚 - 请告诉我:)

1 个答案:

答案 0 :(得分:9)

根据答案It is possible to reference another SQL file from SQL script,在PostgreSQL上,您可以使用\i语法包含另一个SQL文件。我刚刚测试过并且在PostgreSQL 9.6上运行良好:

\i other_script.sql
SELECT * FROM table_1;
SELECT * FROM table_2;

通过@wildplasser评论:

psql -U postgres -h localhost -d postgres < "path to my main sql file"

从psql的角度来看,main_sql文件只是stdin,而stdin没有“filename”。使用-f filename提交名称为

的文件
psql -U postgres -h localhost -d postgres -f filename.sql
  

如何从另一个脚本运行postgres sql脚本?

似乎与How to import external sql scripts from a sql script in PostgreSQL?

相同的问题