有没有办法在纯粹使用postgres sql的名称上创建一个日期时间表。
考虑典型的创建表:
CREATE TABLE someNewTable AS SELECT .... FROM someSourceTable WHERE date >= somedate AND date <somedate;
我需要的是在表名中附加时间戳。时间戳是动态创建的。我知道这不是一种常见的方式,但需要归档目的。那么有没有办法在纯postgres sql中执行此操作?
CREATE TABLE someNewTableYYYYMMDDHHMMSS AS SELECT .... FROM someSourceTable WHERE date >= somedate AND date <somedate;
提前致谢!
答案 0 :(得分:1)
看起来您想要执行动态查询: https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN
然后你需要这样的东西:
execute 'CREATE TABLE someNewTable' ||
to_char(current_timestamp, 'YYYYMMDDHHMMSS') ||
' AS SELECT .... FROM someSourceTable WHERE date >= somedate AND date < somedate;'
或者如果您想在psql
中运行它,那么您还需要使用DO
运算符:
DO $$
begin
execute 'CREATE TABLE someNewTable' ||
to_char(current_timestamp, 'YYYYMMDDHHMMSS') ||
' AS SELECT .... FROM someSourceTable WHERE date >= somedate AND date < somedate;'
end
$$ language plpgsql;