格式 SQL 日期字符串

format SQL date string

我正在尝试获取 select format() 查询中引号之间的日期格式:

select format('CREATE TABLE temporary_table AS
          SELECT id FROM table WHERE created >=%I ORDER BY 1 ASC LIMIT 1','2021-04-01');

我明白了:

CREATE TABLE temporary_table AS
              SELECT table FROM table WHERE created >="2021-04-01" ORDER BY 1 ASC LIMIT 1;

而且我想实际获取单引号之间的日期(因为这在执行时不起作用)

我怎样才能做到这一点?

对于单引号,您需要format() 的说明符%L。喜欢:

SELECT format('CREATE TABLE temporary_table AS
      SELECT id FROM table WHERE created >= %L ORDER BY 1 LIMIT 1','2021-04-01');

参见:

  • Insert text with single quotes in PostgreSQL

当然,只有将输入参数化才有意义。您不会费心使用 format() 作为开始的固定日期。