首页 > 解决方案 > sql文件中的Postgresql命令行变量使用

问题描述

我正在使用 psql 命令将文件绕过参数调用为-v argument=value. 在 SQL 文件中,参数需要用作字符串的一部分。例如prefix_:argument_suffix. 这是行不通的。如果我按照prefix_:argument它的工作原理使用它,但是当涉及到后缀时它不会。

create database这是为了在语句中建立一个数据库名称。

有人可以帮忙吗?

标签: postgresqlcommand-line

解决方案


使用另一个变量,例如:

nd@postgres=# \set argument 'aaa'
nd@postgres=# \set dbname 'foo_':argument'_bar'
nd@postgres=# select :'dbname';
┌─────────────┐
│  ?column?   │
├─────────────┤
│ foo_aaa_bar │
└─────────────┘

nd@postgres=# create database :dbname;
CREATE DATABASE

nd@postgres=# \l
                                    List of databases
┌─────────────┬──────────┬──────────┬─────────────┬─────────────┬───────────────────────┐
│    Name     │  Owner   │ Encoding │   Collate   │    Ctype    │   Access privileges   │
├─────────────┼──────────┼──────────┼─────────────┼─────────────┼───────────────────────┤
│ foo_aaa_bar │ nd       │ UTF8     │ en_US.UTF-8 │ en_US.UTF-8 │                       │
│ postgres    │ postgres │ UTF8     │ en_US.UTF-8 │ en_US.UTF-8 │                       │
│ template0   │ postgres │ UTF8     │ en_US.UTF-8 │ en_US.UTF-8 │ =c/postgres          ↵│
│             │          │          │             │             │ postgres=CTc/postgres │
│ template1   │ postgres │ UTF8     │ en_US.UTF-8 │ en_US.UTF-8 │ =c/postgres          ↵│
│             │          │          │             │             │ postgres=CTc/postgres │
└─────────────┴──────────┴──────────┴─────────────┴─────────────┴───────────────────────┘

推荐阅读