首页 > 解决方案 > Postgresql 不支持查询的时间戳值

问题描述

DECLARE
MAX_upd_date_Entity_Incident timestamp without time zone;
MAX_upd_date_Entity_Incident := (SELECT LAST_UPDATE_DATE::timestamp FROM 
test.table_1 where TABLE_NAME='mac_incidents_d');

execute 'insert into test.table2 (column_name,schema_name,tablename) 
values(''col1'',''col2'',''col3'') from test.table3 X where X.dl_upd_ts::timestamp > '||
MAX_upd_date_Entity_Incident;

上面的查询没有被执行,时间戳值出错,无法读取变量MAX_upd_date_Entity_Incident

如果我们需要将时间戳转换为另一种格式,请建议我。

我可以在 SQL 编辑器中执行查询,但不能使用execute.

标签: postgresqlpostgresql-9.3

解决方案


不要将值作为字符串文字传递。使用占位符并将它们作为“本机”值传递。

values此外,如果要从表中选择源值,则不能使用该子句。插入语句要么是要么 insert into tablename (column_one, column_two) values (value_one, value_two) insert into (column_one, column_two) select c1, c2 from some_table


我也认为不需要动态 SQL:

insert into test.table2 (column_name,schema_name,tablename) 
select col1,col2,col3 
from test.table3 X 
where X.dl_upd_ts::timestamp > MAX_upd_date_Entity_Incident;

如果你过度简化了你的例子并且你确实需要动态 SQL,你应该使用这样的东西:

execute 'insert into test.table2 (column_name,schema_name,tablename) 
select col1,col2,col3) from test.table3 X where X.dl_upd_ts::timestamp > $1' 
    using MAX_upd_date_Entity_Incident;

推荐阅读