问题描述
我希望使用从中返回的字符串
I wish to use the returned string from the query below as a table name for other query.
SELECT 'backup_' || TO_CHAR(CURRENT_DATE,'yyyy-mm-dd')
,您会看到它返回了一个字符串。我希望将其用作另一个查询的输入,例如
as you can see it returns a string. I wish to use it as an input for another query, e.g.
CREATE TABLE (SELECT 'backup_' || TO_CHAR(CURRENT_DATE,'yyyy-mm-dd'))
AS * SELECT FROM backup
选择完成了吗有什么线索吗?
Can it be done? Any clue how?
推荐答案
您将需要使用,通过 DO
块或PL / PgSQL函数(创建或替换功能...语言plpgsql
)。 PostgreSQL使用的普通SQL方言仅在程序PL / PgSQL变体中不支持Dynamic SQL。
You will need to use the PL/PgSQL EXECUTE
statement, via a DO
block or PL/PgSQL function (CREATE OR REPLACE FUNCTION ... LANGUAGE plpgsql
). Dynamic SQL is not supported in the ordinary SQL dialect used by PostgreSQL, only in the procedural PL/PgSQL variant.
DO
$$
BEGIN
EXECUTE format('CREATE TABLE %I AS SELECT * FROM backup', 'backup_' || to_char(CURRENT_DATE,'yyyy-mm-dd'));
END;
$$ LANGUAGE plpgsql;
的%I
和%L
格式说明符分别执行正确的标识符和文字引号。
The format(...)
function's %I
and %L
format-specifiers do proper identifier and literal quoting, respectively.
对于文字,我建议使用 EXECUTE ...使用
而不是 format(。 )
和%L
,但对于表/列之类的标识符,其格式为%I
模式是详细的 quote_ident
调用的一种很好的简洁选择。
For literals I recommend using EXECUTE ... USING
rather than format(...)
with %L
, but for identifiers like table/column names the format %I
pattern is a nice concise alternative to verbose quote_ident
calls.
这篇关于PostgreSQL-动态值作为表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!