首页 > 解决方案 > 再次执行 PostgreSQL 查询的结果以获得最终结果集?

问题描述

我正在寻找一种方法来动态获取所有 PostgreSQL 表中所有 json 属性的列表。

我有查询 1,它将生成一个 sql 语句列表,然后运行该 sql 语句以一次性获得最终输出(如 SQL 服务器中的动态 SQL 概念)。

查询 1 如下所示:


create temporary table test (ordr int, field varchar(1000));

-- Step 1 Create temp table to insert all table/col/json attrbute info

insert into test(ordr,field)
    
    select 0 ordr,'create temporary table temp_table 
    (    table_schema varchar(200)
        ,table_name varchar(200)
        ,column_name varchar(200)
        ,json_attribute varchar(200)
        ,data_type   varchar(50)
    );' 
    
    union

-- Non json type columns

   select 1 ordr, 'insert into temp_table(table_name, column_name,data_type,json_attribute)'
   
   union

-- Json columns with data like json object

    select 
        3 ordr,
        concat('select distinct ''', t.table_name, ''' tbl, ''', c.column_name, ''' col, ''' , c.data_type,''' data_type, '
                ,'jsonb_object_keys(', c.column_name, ') json_attribute', ' from ', t.table_name, 
                ' where jsonb_typeof(' , c.column_name, ') =  ''object'' union') AS field
    from information_schema.tables t
    join information_schema.columns c on c.table_name = t.table_name
    where t.table_schema not in ('information_schema', 'pg_catalog')
        --and table_type = 'BASE TABLE'
        and c.data_type ='jsonb';


--final sql statements to build temp table
--copy all the column "txt" to a separate window and execute it, it will create a temp table "temp_table" which will have all tables/cols/json attributes

    select ordr
        ,(case when t.ordr = (select max(t2.ordr) from test t2) then replace(field,'union','') else field end) txt
    from test t
    union    
    select 9999, ';select * from temp_table;'
    order by 1 ; 

查询 1 输出:这是一个 sql 语句列表

在此处输入图像描述

我正在寻找一种方法来运行查询 1 和查询 1 输出,这将使我一次性获得最终输出。

任何线索或指导将不胜感激。

标签: postgresqlplpgsqlpostgresql-11

解决方案


推荐阅读