Postgresql 并集多个表
我试着遵循这个答案 但是我越来越 错误:在“记录”处或附近出现语法错误 有人有什么想法吗 背景: 历史记录表每晚都会移动到自己的表中,并附加日期 那么history04242018对于每个表名,有没有更好的方法来获取多天的数据 编辑:表将始终具有相同数量的列,因此联合应该很好 编辑2:我只有读权限 更新 根据使用匿名代码块的建议,我现在使用以下代码块:Postgresql 并集多个表,postgresql,Postgresql,我试着遵循这个答案 但是我越来越 错误:在“记录”处或附近出现语法错误 有人有什么想法吗 背景: 历史记录表每晚都会移动到自己的表中,并附加日期 那么history04242018对于每个表名,有没有更好的方法来获取多天的数据 编辑:表将始终具有相同数量的列,因此联合应该很好 编辑2:我只有读权限 更新 根据使用匿名代码块的建议,我现在使用以下代码块: DO $$ declare strSQL text; begin select string_agg(forma
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 $$;
但是我现在得到了错误
描述错误:检索解释计划失败:错误:语法
“DO”位置或附近的错误:58
0条记录受影响
声明
,for
,循环
,执行
是sql的组成部分,而不是普通的sql
(声明
可以在普通的sql
中使用,但含义不同)。因此,如果要从中返回一些数据,您应该将代码包装到或中:
create function get_history(p_day int)
returns table (<structure of history tables here>)
-- or
-- returns setof <history table name>
language plpgsql
as $$
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 to_char(p_day, '"history__"FM09%');
return query execute strSQL;
end $$;
以下是如何使用单个查询构建动态语句:
select string_agg(format('select*from%I.%I',table_schema,table_name),E'union\n')从information_schema.tables(其中table_name类似于'history%')到strSQL中代码>和关于错误:@Abelisto我可以在没有“进入”工作的情况下获得第一部分-不确定我应该如何处理其余部分。我回答的第二行<代码>您需要创建一个存储过程
@JuanCarlosOropeza只读环境谢谢,然而,我只有只读功能,无法生成函数。更新了原始问题-仍然获得error@lookslikeanevo已更新只读环境的答案。请参阅Abellisto-与我的更新相同的错误-甚至尝试了来自sqlfiddle和相同的示例error@lookslikeanevo正如我在问题的最后一条评论中所说:这似乎是框架问题。正如您所看到的,它在纯DB连接上工作。所以更具体一点:您使用什么连接到数据库并执行查询?
create function get_history(p_day int)
returns table (<structure of history tables here>)
-- or
-- returns setof <history table name>
language plpgsql
as $$
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 to_char(p_day, '"history__"FM09%');
return query execute strSQL;
end $$;
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 to_char(p_day, '"history__"FM09%');
-- Prepend "prepare", change the "foo" name as you wish
strSQL := 'prepare foo as ' || strSQL;
execute strSQL;
end $$;
-- Usage
execute foo;
-- And deallocate prepared statement when it does not need anymore:
deallocate foo;