plpgsql - 将天数添加到时间戳

plpgsql - add days to timestamp

我正在 postgress 函数中执行以下 sql。我正在尝试将天数添加到列 rec_cren_dt(带时区的时间戳)。

      EXECUTE format('insert into archive.%s_ar
           select * from schema.%s
           where rec_cren_dt > ''%s'' + INTERVAL ''%s DAY'';
          ', x, x, mindt, tar_date
        );

这给了我错误

ERROR: invalid input syntax for type interval: "2020-05-05 20:52:44.347" LINE 3: where rec_cren_dt > '2020-05-05 20:52:44.347' + I... ^ 

已执行的实际查询 -

QUERY: insert into archive.appl_stng_ar select * from fez.appl_stng where rec_cren_dt > '2020-05-05 20:52:44.347' + INTERVAL '1 DAY'; 

Postgres 缺少此字符串的类型信息。你应该使用显式转换

where rec_cren_dt > ''%s''::timestamp + INTERVAL ''%s DAY'';

或更好,使用USING子句

EXECUTE format('insert into archive.%s_ar
                select * from schema.%s
                where rec_cren_dt >  + INTERVAL ''1 DAY'' * ',
                x, x)
  USING mindt, tar_date;

我看到另一个重要问题 - sql 注入。您使用 %s 占位符表示 table 名称。在这种情况下,您应该使用 %I.

使用 USING 子句,您的语句可以简化:

EXECUTE format('insert into archive.%I'
               ' select * from schema.%I'
               ' where rec_cren_dt > ', x || '_ar', x)
  USING mindt + (tar_date * interval '1 day');