Postgresql Postgres查询中的动态表名

Postgresql Postgres查询中的动态表名,postgresql,Postgresql,有没有办法用另一个表中存储的值替换查询中的表名?这是在PostgresSQL中实现的 乙二醇 元表 col1 | col2 表1 | val1 表2 | val2 我的要求 select * from (select col1 from meta_table where col2 = val2) 如果要更改表的表名,则只需更新表pg_类中的relname列即可。 但要实现这一点,您需要对Postgresql进行管理员访问 查询如下:- update pg_class set relname

有没有办法用另一个表中存储的值替换查询中的表名?这是在PostgresSQL中实现的

乙二醇

元表

col1 | col2
表1 | val1
表2 | val2
我的要求

select * 
from (select col1 from meta_table where col2 = val2)

如果要更改表的表名,则只需更新表pg_类中的relname列即可。 但要实现这一点,您需要对Postgresql进行管理员访问

查询如下:-

update pg_class set relname='new_table_name' where relname='old_table_name';
因此,要在单行中执行此操作,您可以这样做:

update pg_class set relname=(select col1 from meta_table where col2 = val2) where relname='old_table_name';

您可以将
Do
语句与
光标一起使用:

试试这个:

DO $$
DECLARE
  _query text;
  _cursor CONSTANT refcursor := '_cursor';
BEGIN
  _query := 'SELECT * FROM '|| (select col1 from meta_table where col2 = 'val1');
  OPEN _cursor FOR EXECUTE _query;
END
$$;

FETCH ALL FROM _cursor;

最灵活有效的方法可能是使用以下函数动态创建
临时视图

create or replace function f_prepare(tname text, vname text) returns text language plpgsql as $$
begin
    execute format(
        'create or replace temporary view %I as select * from %I',
        vname, tname);
    return vname;
end $$;
然后,您可以以通常的方式使用创建的视图,例如

select f_prepare('pg_class', 'v_class');
select * from v_class where relname = 'pg_database'; -- Index on the source table will be used here
并使用您的代码:

select f_prepare((select col1 from meta_table where col2 = 'val2'), 'v');
select * from v;

与任何其他临时对象一样,创建的视图不会与其他会话冲突,并且会在断开连接时删除。

请参阅。在我看来,这是同一个问题。直接干扰系统目录是一个非常糟糕的建议。应使用“ALTER table…”重命名表。。。改名``