在日常的数据开发过程中,如果是任务紧急,或者是任务量大的时候,我们往往没有足够的时间来专程进行数据字典的维护。但数据字典无论是对于维护数据资产,还是推动企业的数字化转型来说,都有着非凡的意义。
在数据开发过程中,我们可以采用先将任务完成后,对逐个表进行注释,待注释完成后,结合本文中的SQL语句即可方便的构建数据字典。
SELECT
tb.TABLE_NAME,
d.description
FROM
information_schema.tables tb
JOIN pg_class C ON C.relname = tb.
TABLE_NAME LEFT JOIN pg_description d ON d.objoid = C.oid
AND d.objsubid = '0'
WHERE
tb.table_schema = 'test';
-- 查询某schema所有表名称及注释
SELECT C
.relname 表名,
A.attname 字段名,
CAST ( obj_description ( relfilenode, 'pg_class' ) AS VARCHAR ) 字段描述,
concat_ws ( '', T.typname, SUBSTRING ( format_type ( A.atttypid, A.atttypmod ) FROM '\(.*\)' ) ) AS 字段类型 ,
d.description 字段备注
FROM
pg_class C,
pg_attribute A,
pg_type T,
pg_description d
WHERE
A.attnum > 0
AND A.attrelid = C.oid
AND A.atttypid = T.oid
AND d.objoid = A.attrelid
AND d.objsubid = A.attnum
AND C.relname IN ( SELECT tablename FROM pg_tables WHERE schemaname IN ( 'ads' ) AND POSITION ( '_2' IN tablename ) = 0 AND relname LIKE'%ads_scm%' )
ORDER BY
C.relname,
A.attnum;
-- 查询所有列注释,有列序号
SELECT
col.TABLE_NAME,
col.COLUMN_NAME,
col.ordinal_position AS o,
d.description
FROM
information_schema.COLUMNS col
JOIN pg_class C ON C.relname = col.
TABLE_NAME LEFT JOIN pg_description d ON d.objoid = C.oid
AND d.objsubid = col.ordinal_position
WHERE
col.table_schema = 'test'
ORDER BY
col.TABLE_NAME,
col.ordinal_position;
-- 查询schema下所有没注释的表
SELECT
tb.TABLE_NAME,
d.description
FROM
information_schema.tables tb
JOIN pg_class C ON C.relname = tb.
TABLE_NAME LEFT JOIN pg_description d ON d.objoid = C.oid
AND d.objsubid = '0'
WHERE
tb.table_schema = 'test'
AND d.description IS NULL;
-- 查询某schema下所有没注释的表名及列名
SELECT
col.TABLE_NAME,
col.COLUMN_NAME,
col.ordinal_position AS o,
d.description
FROM
information_schema.COLUMNS col
JOIN pg_class C ON C.relname = col.
TABLE_NAME LEFT JOIN pg_description d ON d.objoid = C.oid
AND d.objsubid = col.ordinal_position
WHERE
col.table_schema in ('test')
AND description IS NULL
ORDER BY
col.TABLE_NAME,
col.ordinal_position;
对于数据库的维护来说,数据字典是不可获取的一部分。希望本篇文章能帮助到更多人~