Postgresql 导出表结构信息

项目用了Postgresql 数据库,项目组要出表结构的文档,手写太麻烦,想用slq脚本导出一份。查了一番资料,彷佛没有多好的方法。dump方式导出的脚本太乱,无法直接写在word文档里。只能本身写sql查询出表结构,而后利用pgadmin的导出查询结果的功能,能最快的获取一份整个数据库的表结构信息。虽然不能实现全自动的导出文档,可是对整理文档来讲,仍是节省了很多时间。sql

--查询全部的表字段信息(带表名)数据库

selectspa

(select relname||'--'||(select description from pg_description where objoid=oid and objsubid=0) as comment from pg_class where oid=a.attrelid) as table_name,3d

a.attname as column_name,orm

format_type(a.atttypid,a.atttypmod) as data_type,blog

(case when atttypmod-4>0 then atttypmod-4 else 0 end)data_length,ip

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='p')>0 then 'Y' else 'N' end) as 主键约束,文档

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='u')>0 then 'Y' else 'N' end) as 惟一约束,get

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='f')>0 then 'Y' else 'N' end) as 外键约束,io

(case when a.attnotnull=true then 'Y' else 'N' end) as nullable,

col_description(a.attrelid,a.attnum) as comment

from pg_attribute a

where attstattarget=-1 and attrelid in (select oid from pg_class where relname in(select relname from pg_class where relkind ='r' and relname like 'exg_%'))

order by table_name,a.attnum;

执行sql语句,而后将查询结果导出

使用英文逗号作分隔符,导出csv文件,能够直接在excle中编辑

使用本地字符集能够防止乱码

 用excle打开导出的csv文件,由于导出的是全部的表结构信息,因此要先分表,拷贝第一行表头信息,分别插入到每张表的前面(插入行的快捷键本身网上找吧)。

作完上面的步骤,就能够把表结构信息粘帖到word文档里了;

在粘贴完毕后,要选择使用目标格式

表格出来了

这个时候全部的表结构是一张大表格,能够用Ctrl+shift+enter把表格分开

附:其它sql脚本

--查询表名和描述

select relname as table_name,(select description from pg_description where objoid=oid and objsubid=0) as comment from pg_class where relkind ='r' and relname like 'exg_%' order by table_name;

 

--查询表字段信息

select

a.attname as column_name,

format_type(a.atttypid,a.atttypmod) as data_type,

(case when atttypmod-4>0 then atttypmod-4 else 0 end)data_length,

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='p')>0 then 'Y' else 'N' end) as 主键约束,

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='u')>0 then 'Y' else 'N' end) as 惟一约束,

(case when (select count(*) from pg_constraint where conrelid = a.attrelid and conkey[1]=attnum and contype='f')>0 then 'Y' else 'N' end) as 外键约束,

(case when a.attnotnull=true then 'Y' else 'N' end) as nullable,

col_description(a.attrelid,a.attnum) as comment

from pg_attribute a

where attstattarget=-1 and attrelid = (select oid from pg_class where relname ='exg_ms_alarm');--表名

相关文章
相关标签/搜索