使用动态查询跨不同表的PostgreSQL查询

时间:2019-04-23 08:11:25

标签: postgresql

我正在尝试获取一个可以放置在十个不同表之一中的客户ID。我不想对这些表名进行硬编码来找到它,所以我尝试了如下的postgresql函数。

create or replace FUNCTION test() RETURNS SETOF RECORD AS $$
DECLARE
 rec record;
BEGIN
  select id from schema.table_0201_0228 limit 1 into rec;
  return next rec;

  select id from schema.table_0301_0331 limit 1 into rec;
  return next rec;
END $$ language plpgsql;

select * from test() as (id int)

由于我对Postgresql函数的用法不熟悉,如何改进代码以将'schema.table1'替换为变量,循环每个表并返回结果?

注意:表名可能会随着时间的变化而变化。例如,table_0201_0228和table_0301_0331分别用于2月和3月。

1 个答案:

答案 0 :(得分:1)

为此您需要动态SQL:

create or replace FUNCTION test(p_schema text) 
  RETURNS table(id int)
AS $$
DECLARE
  l_tab record;
  l_sql text;
BEGIN
  for l_tab in (select schemaname, tablename 
                from pg_tables 
                where schemaname = p_schema) 
  loop
    l_sql := format('select id from %I.%I limit 1', l_tab.schemaname, l_tab.tablename);
    return query execute l_sql;
  end loop;
END $$ 
language plpgsql;

我将模式名称作为参数,但是您当然可以对其进行硬编码。由于该函数定义为returns table,因此在使用时无需指定列名:

select *
from test('some_schema');
相关问题