create table foo (i int, j text);
select table_schema, table_name, column_name , ordinal_position
from information_schema.columns where table_name = 'foo';
Output
table_schema table_name column_name ordinal_position
public foo i 1
public foo j 2
通过使用第二条语句,我需要形成一个选择查询select i, j from public.foo
。一个简单的函数就足够了,如果我们传递表名,则结果可以是select语句的字符串
您可以使用聚合:
select concat_ws(' ',
'select',
string_agg(column_name, ', ' order by ordinal_position),
'from',
table_schema || '.' || table_name
) q
from information_schema.columns
where table_name = 'foo'
group by table_schema, table_name
或不带group by
子句:
select concat_ws(' ',
'select',
string_agg(column_name, ', ' order by ordinal_position),
'from',
max(table_schema) || '.' || max(table_name)
) q
from information_schema.columns
where table_name = 'foo' and table_schema = 'public'
| q || :-------------------------- ||从public.foo中选择i,j |