plpgsql-将天数添加到时间戳中

问题描述 投票:0回答:1

我正在后端函数中执行以下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'; 
timestamp plpgsql intervals dynamic-sql
1个回答
0
投票

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 > $1 + INTERVAL ''1 DAY'' * $2',
                x, x)
  USING mindt, tar_date;

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

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

EXECUTE format('insert into archive.%I'
               ' select * from schema.%I'
               ' where rec_cren_dt > $1', x || '_ar', x)
  USING mindt + (tar_date * interval '1 day');
© www.soinside.com 2019 - 2024. All rights reserved.