【发布时间】:2018-04-26 02:27:03
【问题描述】:
我试图遵循这个答案
Dynamic UNION ALL query in Postgres
但我得到了 错误:“记录”处或附近的语法错误
DECLARE
rec record;
strSQL text;
BEGIN
FOR
rec in
select table_name
from
information_schema.tables
where
table_name like 'history%'
loop
strSQL : = strSQL || 'Select * from' || rec.table_schema ||'.'|| rec.table_name || ' UNION ';
end loop;
-- remove last ' UNION ' from strSQL
--strSQL := 'Select row_number() over(order by rowid ) as row_num from (' || strSQL || ')';
execute strSQL;
有人有什么想法吗?
背景: 历史表每晚都会移动到自己的表中,并附加日期。
所以 history04242018 对于每个表名,有没有更好的方法来获取多天的数据?
编辑:表总是有相同数量的列,所以联合应该没问题
edit2:我只有读取权限。
更新 在使用匿名代码块的建议下,我现在使用以下内容:
DO
$$
declare
strSQL text;
begin
select
string_agg(format('select * from %I.%I', table_schema, table_name), E' union\n')
into strSQL
from information_schema.tables
where table_name like 'history%';
execute strSQL ;
end $$;
但是我现在得到错误
描述错误:无法检索 EXPLAIN 计划:错误:语法 在“DO”位置或附近出错:58
0 条记录受影响
【问题讨论】:
-
以下是如何使用单个查询构建动态语句:
select string_agg(format('select * from %I.%I', table_schema, table_name), E' union\n') into strSQL from information_schema.tables where table_name like 'history%'; -
@Abelisto 我可以在没有“进入”工作的情况下获得第一部分 - 不太确定我应该如何处理其余部分。
-
我的回答第二行
You need create a store procedure -
@JuanCarlosOropeza 只读环境
标签: postgresql