【问题标题】:How to run postgres sql script from another script?如何从另一个脚本运行 postgresql 脚本?
【发布时间】:2015-01-14 10:58:19
【问题描述】:

我有一堆在数据库中创建表的 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"

除了调用其他脚本之外,该文件执行良好。

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

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

【问题讨论】:

  • 您尝试在哪个操作系统中完成此操作?
  • psql -U postgres -h localhost -d postgres &lt; "path to my main sql file" :从 psql 的角度来看, main_sql 文件只是标准输入。标准输入没有“文件名”;使用-f filename 提交带有名称的文件。
  • 谢谢@wildplasser,就是这样 :) rchang 我是在 Windows 7 Professional 上做的
  • @wildplasser 我可以建议您将其发布为答案吗?刚才对我有帮助。
  • 问题是:对于 unix 人来说,这个解决方案太琐碎了,以至于很难作为答案发布......

标签: postgresql


【解决方案1】:

根据答案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 文件只是标准输入,标准输入没有“文件名”。使用-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?

【讨论】:

  • 有没有办法从 PgAdmin4 或只有我从控制台运行它?
猜你喜欢
  • 1970-01-01
  • 2014-05-04
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
相关资源
最近更新 更多