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');--表名

相關文章
相關標籤/搜索