简体   繁体   English

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

[英]How to run postgres sql script from another script?

I have a bunch of SQL scripts that create tables in the database.我有一堆在数据库中创建表的 SQL 脚本。 Each table is located in a separate file so that editing them is much easier.每个表都位于一个单独的文件中,因此编辑它们要容易得多。

I wanted to prepare a single SQL script that will create the full schema, create tables, insert test data and generate sequences for the tables.我想准备一个单独的 SQL 脚本,它将创建完整的模式、创建表、插入测试数据并为表生成序列。

I was able to do such thing for oracle database but I am having problems with postgres.我能够为 oracle 数据库做这样的事情,但是我在使用 postgres 时遇到了问题。 The thing is - I do not know how to run the table creating script from another script.问题是 - 我不知道如何从另一个脚本运行表创建脚本。

In oracle I do it using the following syntax:在 oracle 中,我使用以下语法进行操作:

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

And everything works like a charm.一切都像魅力一样。

In postgres I was trying to search for something alike and found this:在 postgres 中,我试图搜索类似的东西并找到了这个:

\ir 'relative path to the file'

Unfortunately when I run my main script I get the message:不幸的是,当我运行主脚本时,我收到以下消息:

No such file or directory.

The example call is here:示例调用在这里:

\ir './tables/map_user_groups.sql'

I use Postgres 9.3.我使用 Postgres 9.3。 I tried to run the script using psql:我尝试使用 psql 运行脚本:

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

The file executes fine except for the calling of those other scripts.除了调用其他脚本外,该文件执行正常。

Does anybody know how to solve the problem ?有人知道如何解决问题吗?

If something in the question is unclear - just let me know :)如果问题中的某些内容不清楚-请告诉我:)

Based on the answer It is possible to reference another SQL file from SQL script , on PostgreSQL, you can include another SQL's files just using the \\i syntax.根据答案It is possible to reference another SQL file from SQL script ,在 PostgreSQL 上,您可以仅使用\\i语法包含另一个 SQL 的文件。 I just tested and is working good on PostgreSQL 9.6:我刚刚测试过并且在 PostgreSQL 9.6 上运行良好:

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

By the @wildplasser comment:通过@wildplasser 评论:

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

From psql's perspective the main_sql file is just stdin, and stdin has no "filename".从 psql 的角度来看, main_sql文件只是 stdin,而 stdin 没有“文件名”。 Use -f filename to submit a file with a name:使用-f filename提交具有名称的文件:

 psql -U postgres -h localhost -d postgres -f filename.sql

How to run postgres sql script from another script?如何从另一个脚本运行 postgres sql 脚本?

Seems the same question as: How to import external sql scripts from a sql script in PostgreSQL?似乎与以下问题相同:如何从 PostgreSQL 中的 sql 脚本导入外部 sql 脚本?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM