简体   繁体   English

sql文件中的Postgresql命令行变量用法

[英]Postgresql command line variable usage in sql file

I am using psql command to call a file bypassing argument as -v argument=value .我正在使用 psql 命令将文件绕过参数调用为-v argument=value In the SQL file, the argument needs to be used as part of a string.在 SQL 文件中,参数需要用作字符串的一部分。 For example prefix_:argument_suffix .例如prefix_:argument_suffix This is not working.这是行不通的。 If I use it as prefix_:argument it works, but when it comes to the suffix it doesn't.如果我将它用作prefix_:argument它会起作用,但是当涉及到后缀时它不会。

This is for building a database name in the create database statement.这是用于在create database语句中构建数据库名称。

Can somebody help with this?有人可以帮忙吗?

Use another variable like:使用另一个变量,如:

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 │
└─────────────┴──────────┴──────────┴─────────────┴─────────────┴───────────────────────┘

The string could be built as该字符串可以构建为

'prefix_' || :'variable' || '_suffix'

To use it in a CREATE DATABASE statement, you will have to use dynamic SQL in a function:要在CREATE DATABASE语句中使用它,您必须在函数中使用动态 SQL:

CREATE FUNCTION pg_temp.mkdb(var text) RETURNS void
   LANGUAGE plpgsql STRICT AS
$$BEGIN
   EXECUTE format('CREATE DATABASE %I;', 'prefix_' || var || '_suffix');
END;$$;

SELECT pg_temp.mkdb(:'variable');

Since the function is created in the temporary schema, it will exist only in this database session.由于该函数是在临时模式中创建的,因此它将仅存在于该数据库会话中。

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

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