PostgreSQL:如何将动态查询添加为查询列?

时间:2018-01-26 09:51:14

标签: sql postgresql

我的查询:

select table_name,column_name,seq_name,nextval(seq_name::TEXT)
from 
(
  SELECT table_name,column_name,SUBSTRING(column_default,
  strpos(column_default,'(')+2,
  strpos(column_default,'::')-1 -(strpos(column_default,'(')+2)) as seq_name
  FROM information_schema.columns 
  WHERE column_default LIKE 'nextval%'
) t;

如何向查询中添加另一列从当前表中计算max的列?像这样:

(select coalesce(max(fname_id),1) from <current table>) as realmax

问题是当前行中的表名是字符串

2 个答案:

答案 0 :(得分:1)

您可以创建功能:

create or replace function ms(_t text, _a text) returns int as $$
declare
 _m int;
begin
  execute format('select coalesce(max(%I),1) from %I',_a,_t) into _m;
 return _m;
end;
$$ language plpgsql;

并使用它:

select table_name,column_name,seq_name,nextval(seq_name::TEXT)
from
(SELECT table_name,column_name,SUBSTRING(column_default,
strpos(column_default,'(')+2,
strpos(column_default,'::')-1 -(strpos(column_default,'(')+2)) as seq_name
FROM information_schema.columns WHERE column_default LIKE 'nextval%') t;

另外请注意,此处不使用模式名称。可能需要它

答案 1 :(得分:0)

这可以在没有动态SQL的情况下完成:

select table_name,column_name, nextval(seq_name), 
       (xpath('/table/row/max/text()', xml))[1]::text::int as max_val
from (
  SELECT table_name,
         column_name,
         table_schema,
         query_to_xml(format('select coalesce(max(%I),1) as max from %I.%I', column_name, table_schema, table_name), false, false, '') as xml
  FROM information_schema.columns 
  where column_default LIKE 'nextval%'
) t;

这是[{3}}

的变体