【问题标题】:Dyanmic Table name in Postgres queryPostgres查询中的动态表名
【发布时间】:2020-04-27 06:46:16
【问题描述】:

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

例如

元表

col1    | col 2
Table 1 | val1
Table 2 | val2

我的要求

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

【问题讨论】:

标签: postgresql


【解决方案1】:

可能最灵活有效的方法是使用函数动态创建temporary view

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;

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

【讨论】:

    【解决方案2】:

    如果要更改表的表名,则只需更新表 pg_class 中的 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';
    

    【讨论】:

    • 直接弄乱系统目录是一个真的糟糕的建议。应该使用 `ALTER TABLE ... RENAME`` 重命名表
    【解决方案3】:

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

    试试这个:

    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;
    

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多