如何查找表中特定列以及架构中所有表的数据字段的最大长度

问题描述 投票:0回答:1

晚上好我们在数据库的多个模式中有多个表。我们打算找出所有表和所有模式的表中每一列的最大大小。

示例列名称:a,b,c,d,e,f,g模式名称示例:A,B,C,D

预期输出:column_name Max_size_of_column

或column_name Max_size_of_column column_table table_schema

我已经尝试过以下查询,但无法获得所需的输出。

SELECT (select column_name from INFORMATION_SCHEMA.COLUMNS
where table_name='building'), 
select max(length(select column_name from INFORMATION_SCHEMA.COLUMNS 
where table_name='building')) from from INFORMATION_SCHEMA.COLUMNS 
where table_name='building'
group by column_name;

请帮助我们获得所需的输出。谢谢

postgresql-9.5
1个回答
0
投票

您需要某种动态SQL来解决此类问题。但是在Postgres中,无需PL / pgSQL函数即可完成此操作,类似于方法from this answer,但将max()和length()组合在一起:

with all_lengths as (
  select table_schema, table_name, column_name,
         query_to_xml(format('select max(length(%I)) from %I.%I', column_name, table_schema, table_name), false, true, '') as xml_max
  from information_schema.columns
  where table_schema in ('public') -- add the schemas you want here
    and data_type in ('text', 'character varying')
)
select table_schema, table_name, column_name, 
       (xpath('/row/max/text()', xml_max))[1]::text::int as max_length
from all_lengths
;

我没有可用的Postgres 9.5,但我认为该版本也应适用于该旧版本。

如果只需要特定的列,而不是文本或varchar类型的所有列,只需在CTE中将and data_type in (..)条件更改为and column_name in (...)

© www.soinside.com 2019 - 2024. All rights reserved.