如何在 PostgreSQL 中描述 SQL 查询的列(获取它们的名称、数据类型等)
How to describe columns (get their names, data types, etc.) of a SQL query in PostgreSQL
我需要一种方法从 SELECT 查询(游标)中获取 "description" 列,例如它们的名称、数据类型、精度、小数位数等,在 PostgreSQL 中(或者更好 PL/pgSQL).
我正在从 Oracle PL/SQL 过渡,在那里我可以使用内置过程 dbms_sql.describe_columns 获得此类描述。它 return 是一个记录数组,一个给定(已解析)游标的每一列。
此类查询的示例:
select col1 from tab where col2 = :a
我需要一个 API(或解决方法)可以这样调用(希望如此):
select query_column_description('select col1 from tab where col2 = :a');
这将 return 类似于:
{{"col1","numeric"}}
为什么?我们构建视图,其中这些查询成为单独的列。例如,视图的查询如下所示:
select (select col1 from tab where col2 = t.colA) as col1::numeric
from tab_main t
http://sqlfiddle.com/#!17/21c7a/2
您可以使用系统 table :
第一步使用您的查询创建一个临时视图(没有 where 子句)
create or replace view temporary view a_view as
select col1 from tab
然后 select
select
row_to_json(t.*)
from (
select
column_name,
data_type
from
information_schema.columns
where
table_schema = 'public' and
table_name = 'a_view'
) as t
我需要一种方法从 SELECT 查询(游标)中获取 "description" 列,例如它们的名称、数据类型、精度、小数位数等,在 PostgreSQL 中(或者更好 PL/pgSQL).
我正在从 Oracle PL/SQL 过渡,在那里我可以使用内置过程 dbms_sql.describe_columns 获得此类描述。它 return 是一个记录数组,一个给定(已解析)游标的每一列。
此类查询的示例:
select col1 from tab where col2 = :a
我需要一个 API(或解决方法)可以这样调用(希望如此):
select query_column_description('select col1 from tab where col2 = :a');
这将 return 类似于:
{{"col1","numeric"}}
为什么?我们构建视图,其中这些查询成为单独的列。例如,视图的查询如下所示:
select (select col1 from tab where col2 = t.colA) as col1::numeric
from tab_main t
http://sqlfiddle.com/#!17/21c7a/2
您可以使用系统 table :
第一步使用您的查询创建一个临时视图(没有 where 子句)
create or replace view temporary view a_view as
select col1 from tab
然后 select
select
row_to_json(t.*)
from (
select
column_name,
data_type
from
information_schema.columns
where
table_schema = 'public' and
table_name = 'a_view'
) as t