Postgresql 導出表結構信息


項目用了Postgresql 數據庫,項目組要出表結構的文檔,手寫太麻煩,想用slq腳本導出一份。查了一番資料,似乎沒有多好的方法。dump方式導出的腳本太亂,沒法直接寫在word文檔里。只能自己寫sql查詢出表結構,然后利用pgadmin的導出查詢結果的功能,能最快的獲取一份整個數據庫的表結構信息。雖然不能實現全自動的導出文檔,但是對整理文檔來說,還是節省了不少時間。

--查詢所有的表字段信息(帶表名)

select

(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,

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM