【问题标题】:How to get the fields' information from a SQL statement in PostgreSQL?如何从 PostgreSQL 中的 SQL 语句中获取字段信息?
【发布时间】:2022-01-29 04:26:56
【问题描述】:

我想从 SQL 语句中获取字段的描述。也就是我要创建一个函数,使用sql语句作为入参,返回一个jsonb值来描述字段的信息。

如果我知道表名,我可以这样做:

SELECT column_name, data_type
FROM information_schema."columns"
WHERE "table_name"='TABLE-NAME'

但是如果我只有select sql语句,比如select 0::bigint as fid, 'A'::text as fname;,我怎么才能得到column_namedata_type一个函数呢。

下面是我知道表名时 then 函数的结构:

create or replace function public.getfieldsfromtable(vtable text)
    returns jsonb
    language 'plpgsql'
    cost 100
    volatile 
as $body$ declare
    jfields jsonb='[]'::jsonb;
begin
    select 
        array_to_json(array_agg(row_to_json(t))) 
    into jfields
    from (
        select column_name, data_type
        from information_schema."columns"
        where "table_name"=vtable
    ) t;
    return jfields;
end;
$body$;

但是如果我只有一个 Select SQL 语句,我该怎么办?

create or replace function public.getfieldsfromsql(vsql text)
    returns jsonb
    language 'plpgsql'
    cost 100
    volatile 
as $body$ declare
    jfields jsonb='[]'::jsonb;
begin
    ... what can i do?
    return jfields;
end;
$body$;

【问题讨论】:

    标签: postgresql select field


    【解决方案1】:

    如果你在 C 扩展中做到这一点,这很容易,但在 PL/pgSQL 中几乎是不可能的。对于存储过程,没有API,如何在不执行查询的情况下检测结果结构。

    【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2016-09-16
    相关资源
    最近更新 更多