Postgresql 匯出表結構資訊

來源:互聯網
上載者:User

標籤:des   blog   http   io   ar   os   使用   for   檔案   

項目組要出表結構的文檔,手寫太麻煩,想用slq指令碼匯出一份。

--查詢所有的表欄位資訊(帶表名)

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中編輯

使用本地字元集可以防止亂碼

?

附:其它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‘);--表名

Postgresql 匯出表結構資訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.