Cute Happy Ghost
본문 바로가기
DB/Postgresql

[PostgreSQL] 테이블 정의서 쿼리

by JENN_tech7 2022. 8. 30.
728x90
SMALL

맨 아래 스키마명만 자신의 스키마명으로 바꿔주면 됨

select 
T.table_catalog as "db명" 
, T.table_schema as "스키마명" 
, T.table_name as "테이블ID" 
, coalesce((select PD.DESCRIPTION 
from PG_STAT_USER_TABLES PS 
, PG_DESCRIPTION PD 
where PS.RELNAME = T.table_name 
 and PS.schemaname = T.table_schema 
 and PS.RELID = PD.OBJOID 
 and PD.OBJSUBID = 0 ), 'NULL' 
) as "테이블명" 
,   T.ordinal_position as "컬럼순서" 
, T.column_name as "컬럼ID" 
, coalesce((select PD.DESCRIPTION 
from PG_STAT_ALL_TABLES PS 
, PG_DESCRIPTION PD 
, PG_ATTRIBUTE PA 
where PS.SCHEMANAME = T.table_schema 
and PS.RELNAME = T.table_name 
and PA.ATTNAME = T.column_name 
and PS.RELID = PD.OBJOID 
and PD.OBJSUBID <> 0 
and PD.OBJOID = PA.ATTRELID 
and PD.OBJSUBID = PA.ATTNUM ), 'NULL' 
) as "컬럼명" 
, T.UDT_NAME as "DATA TYPE" 
-- , T.DATA_TYPE 
, case 
when T.data_type_gb = 1 then T.VCHAR 
when T.data_type_gb = 2 then 
case 
when T.SCAL = '0' then T.NUMB 
else T.NUMB || ',' || T.SCAL 
end 
when T.data_type_gb = 3 then null 
end as "컬럼길이" 
, 
T.NULL_YN as "널 유무" 
, 
( 
select 
case 
when CC.column_name is not null then 'PK' 
else ' ' 
end 
from 
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC 
, 
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CC 
where 
TC.TABLE_CATALOG = T.table_catalog 
and TC.TABLE_NAME = T.table_name 
and TC.TABLE_SCHEMA = T.table_schema 
and TC.CONSTRAINT_TYPE = 'PRIMARY KEY' 
and TC.TABLE_CATALOG = CC.TABLE_CATALOG 
and TC.TABLE_SCHEMA = CC.TABLE_SCHEMA 
and TC.TABLE_NAME = CC.TABLE_NAME 
and TC.CONSTRAINT_NAME = CC.CONSTRAINT_NAME 
and CC.column_name = T.column_name 
) as "PKEY 여부" 
, 
T.DATA_TYPE 
from 
( 
select 
table_catalog 
, table_schema 
, table_name 
, ordinal_position 
, column_name 
, UDT_NAME 
, DATA_TYPE 
, case 
when character_maximum_length is not null then 1 
when numeric_precision is not null then 2 
else 3 
end data_type_gb 
, to_char(case when character_maximum_length is not null then character_maximum_length else null end, 'FM99999999') VCHAR 
, to_char(case when numeric_precision is not null then 
case when numeric_precision > 0 then numeric_precision 
else numeric_precision_radix end 
else null end, 'FM99999999') NUMB 
, to_char(case when numeric_scale > 0 then numeric_scale else 0 end , 'FM99999999') SCAL 
, case 
when is_nullable = 'NO' then 'NN' 
else '' 
end NULL_YN 
, column_default 
from 
information_schema.columns 
where 
table_schema in ('public') 
-- and table_name in ('ncom_id_mstr') 
order by 
table_catalog 
, table_schema 
, table_name 
, ordinal_position 
) T 
order by 
T.table_catalog 
, T.table_schema 
, T.table_name 
, T.ordinal_position ;

 

728x90
LIST

댓글