以函数为值执行 \set 命令
Execute \set command with function as value
在我的一个 SQL Postgre 脚本中SQL 我想声明一个值,以便我可以在脚本其余部分的多个位置使用它。
这是我根据 所做的:
\set cat_id uuid_generate_v4()
insert into categories (id, name) values (:cat_id, 'Category 1')
insert into other_table (id, category_id) values (uuid_generate_v4(), :cat_id)
问题是变量cat_id
没有一次取值。它只是将 :cat_id
替换为 uuid_generate_v4()
。因此,两个插入查询中的值不相同。
如何才能给cat_id
函数执行的值?
谢谢。
您可以将匿名 DO
块与使用新 UUID 初始化的变量一起使用。
DO
$$
DECLARE
cat_id uuid = uuid_generate_v4();
BEGIN
INSERT INTO categories
(id,
name)
VALUES (cat_id,
'Category 1');
INSERT INTO other_table
(id,
category_id)
VALUES (uuid_generate_v4(),
cat_id),
END;
$$
LANGUAGE PLpgSQL;
当 :cat_id
包含 uuid_generate_v4()
时,您将其用作宏。 \set
psql 中的变量既可以用作宏,也可以用作变量。
Q: How can I do to give cat_id the value of the execution of the function
?
select uuid_generate_v4() as cat_id \gset
文档:
\gset [ prefix ]
Sends the current query input buffer to the server and stores the query's output into
psql variables (see Variables). The query to be executed must return exactly one row.
Each column of the row is stored into a separate variable, named the same as the column.
请注意,之后将其注入到语句中,要使用的语法是 :'cat_id'
以便它被正确地引用为文字。
在我的一个 SQL Postgre 脚本中SQL 我想声明一个值,以便我可以在脚本其余部分的多个位置使用它。
这是我根据
\set cat_id uuid_generate_v4()
insert into categories (id, name) values (:cat_id, 'Category 1')
insert into other_table (id, category_id) values (uuid_generate_v4(), :cat_id)
问题是变量cat_id
没有一次取值。它只是将 :cat_id
替换为 uuid_generate_v4()
。因此,两个插入查询中的值不相同。
如何才能给cat_id
函数执行的值?
谢谢。
您可以将匿名 DO
块与使用新 UUID 初始化的变量一起使用。
DO
$$
DECLARE
cat_id uuid = uuid_generate_v4();
BEGIN
INSERT INTO categories
(id,
name)
VALUES (cat_id,
'Category 1');
INSERT INTO other_table
(id,
category_id)
VALUES (uuid_generate_v4(),
cat_id),
END;
$$
LANGUAGE PLpgSQL;
当 :cat_id
包含 uuid_generate_v4()
时,您将其用作宏。 \set
psql 中的变量既可以用作宏,也可以用作变量。
Q: How can I do to give cat_id the value of the execution of the function ?
select uuid_generate_v4() as cat_id \gset
文档:
\gset [ prefix ]
Sends the current query input buffer to the server and stores the query's output into psql variables (see Variables). The query to be executed must return exactly one row.
Each column of the row is stored into a separate variable, named the same as the column.
请注意,之后将其注入到语句中,要使用的语法是 :'cat_id'
以便它被正确地引用为文字。