将查询创建为字符串并在 PostgreSQL 10 中执行
Create the query as a string and execute that in PostgreSQL 10
我正在尝试将查询创建为字符串并在 Postgre 中执行它SQL 10.
据我所知,我可以使用 EXECUTE 命令从定义的字符串中执行我的查询。
不幸的是,我遇到了一个错误:SQL 错误 [42601]:错误:"execute"
处或附近的语法错误
下面是我的代码:
drop table if exists delinquent;
create table delinquent
(
report_date date
,account_id text
)
;
INSERT INTO delinquent VALUES('2019-07-23', 'a1234');
INSERT INTO delinquent VALUES('2019-07-23', 'b5679');
--------------
drop table if exists output1;
create temp table output1
(
report_date date
,account_id text
)
;
--------------
do $$
declare table_name text := 'delinquent';
begin
truncate table output1;
insert into output1
execute concat('select * from ',table_name);
end; $$;
select * from output1;
有人知道哪里出了问题以及该怎么办吗?
非常感谢,
您需要运行 将完整的 INSERT 语句作为动态 SQL。并构建动态 SQL,强烈建议使用 format()
以正确处理标识符和文字:
do $$
declare
table_name text := 'delinquent';
some_value text := 'a1234';
begin
truncate table output1;
execute format('insert into output1 select * from %I where some_column = %L',
table_name, some_value);
end; $$;
select *
from output1;
我正在尝试将查询创建为字符串并在 Postgre 中执行它SQL 10.
据我所知,我可以使用 EXECUTE 命令从定义的字符串中执行我的查询。
不幸的是,我遇到了一个错误:SQL 错误 [42601]:错误:"execute"
处或附近的语法错误下面是我的代码:
drop table if exists delinquent;
create table delinquent
(
report_date date
,account_id text
)
;
INSERT INTO delinquent VALUES('2019-07-23', 'a1234');
INSERT INTO delinquent VALUES('2019-07-23', 'b5679');
--------------
drop table if exists output1;
create temp table output1
(
report_date date
,account_id text
)
;
--------------
do $$
declare table_name text := 'delinquent';
begin
truncate table output1;
insert into output1
execute concat('select * from ',table_name);
end; $$;
select * from output1;
有人知道哪里出了问题以及该怎么办吗?
非常感谢,
您需要运行 将完整的 INSERT 语句作为动态 SQL。并构建动态 SQL,强烈建议使用 format()
以正确处理标识符和文字:
do $$
declare
table_name text := 'delinquent';
some_value text := 'a1234';
begin
truncate table output1;
execute format('insert into output1 select * from %I where some_column = %L',
table_name, some_value);
end; $$;
select *
from output1;