본문 바로가기
데이터베이스/Postgresql

[PostgreSQL] 테이블 정의서 쿼리

by cbwstar 2021. 7. 27.
728x90
반응형


-- table정의서 추출
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 ('naqsifh')
-- 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
반응형

댓글



"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

loading