【发布时间】: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_name和data_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