不要将输入值连接到动态SQL中。并且永远不要将
我正在挠头,试图修复以下问题:
create or replace procedure my_schema.Test()
as $$
declare
today date = now();
begin
drop table if exists my_schema.tst_table;
create table my_schema.tst_table (
todays_date varchar );
execute('
insert into my_schema.tst_table
values (' || today || ')
');
end;
$$
language plpgsql;
基本上,我试图将当前日期动态插入到一个表中,该表将在以后的步骤中使用。
我面临的问题是,由于今天的变量看起来像"2022-02-11",并且由于我正在动态插入记录,postgres正在解释"-"作为减号,并将值2009插入到我的表中。
有人能解决这个问题吗?
date
值存储在varchar
列中:
create or replace procedure my_schema.Test()
as $$
declare
today date := current_date;
begin
drop table if exists my_schema.tst_table;
create table my_schema.tst_table
(
todays_date date
);
execute('
insert into my_schema.tst_table
values ($1)
') using today;
end;
$$
language plpgsql;
但是创建一个表来存储current_date
的值似乎有点过头了。
您可以使用强制转换运算符将值转换为VARCHAR
数据类型:
execute('
insert into my_schema.tst_table
values ('today'::VARCHAR)
');