2017-10-19 63 views
0

我需要一种方法来从SELECT查询(游标)中获取列的“描述”,例如它们的名称,数据类型,精度,比例等,在PostgreSQL(或更好的PL/pgSQL)中。如何在PostgreSQL中描述SQL查询的列(获取它们的名称,数据类型等)

我正在从Oracle PL/SQL过渡,我可以使用内置过程dbms_sql.describe_columns获取此类描述。它返回一个记录数组,每个记录对应给定(已解析)游标的每一列。

教育局已就实施过(https://www.enterprisedb.com/docs/en/9.0/oracompat/Postgres_Plus_Advanced_Server_Oracle_Compatibility_Guide-127.htm#P13324_681237

这样的查询的

一个例子:

select col1 from tab where col2 = :a 

我需要一个API(或解决方法)可以被称为像这样(希望):

select query_column_description('select col1 from tab where col2 = :a'); 

,将返回类似于:

{{"col1","numeric"}} 

为什么?我们构建这些查询成为单独列的视图。例如,视图的查询将如下所示:

select (select col1 from tab where col2 = t.colA) as col1::numeric 
    from tab_main t 
+0

类似的东西可用psycopg2(https://stackoverflow.com/questions/10252247/how-do-i-get-a-list-of-column-names-from-a-psycopg2-cursor),但我希望我能保持在PL/pgSQL中,所以我不必为此处理(安装/学习/等)psycopg2(也许还有一些其他很酷/我需要发现的功能) –

+0

有没有内置在服务器端。在客户端,我知道JDBC可以做到这一点,我也猜测ODBC。我假设这两个接口都使用[SPI](https://www.postgresql.org/docs/current/static/spi-interface-support.html)。 –

+0

如果你没有问题,请提出答案。谢谢。 – Indent

回答

0

http://sqlfiddle.com/#!17/21c7a/2

您可以使用系统表:

第一步创建您的查询的临时视图(没有where子句中)

create or replace view temporary view a_view as 
    select col1 from tab 

然后选择

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 
+0

谢谢@Indent。我将通过创建临时视图来使用您的解决方法。 –

+0

好的,很酷。如果你觉得没问题,请提出答案。谢谢。祝你有美好的一天。 – Indent

+0

对不起@Indent,因为我的低信誉,我无法赞成。然而你的答案帮了我很多。再次感谢。 –

相关问题