postgresql 實現獲取所有表名,字段名,字段類型,註釋
獲取表名及註釋:
select relname as tabname,cast(obj_description(relfilenode,'pg_class') as varchar) as comment from pg_class c where relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%' order by relname
過濾掉分表:
加條件 and relchecks=0
即可
獲取字段名、類型、註釋、是否為空:
SELECT col_description(a.attrelid,a.attnum) as comment,format_type(a.atttypid,a.atttypmod) as type,a.attname as name, a.attnotnull as notnull FROM pg_class as c,pg_attribute as a where c.relname = '表名' and a.attrelid = c.oid and a.attnum>0
補充:PostgreSQL查詢表主鍵及註釋內容
網上關於pgSql獲取表主鍵的內容都是千篇一律,並且對於存在多主鍵的場景不支持。
附上測試後可獲取多個主鍵字段值的SQL
SELECT string_agg(DISTINCT t3.attname,',') AS primaryKeyColumn ,t4.tablename AS tableName , string_agg(cast(obj_description(relfilenode,'pg_class') as varchar),'') as comment FROM pg_constraint t1 INNER JOIN pg_class t2 ON t1.conrelid = t2.oid INNER JOIN pg_attribute t3 ON t3.attrelid = t2.oid AND array_position(t1.conkey,t3.attnum) is not null INNER JOIN pg_tables t4 on t4.tablename = t2.relname INNER JOIN pg_index t5 ON t5.indrelid = t2.oid AND t3.attnum = ANY (t5.indkey) LEFT JOIN pg_description t6 on t6.objoid=t3.attrelid and t6.objsubid=t3.attnum WHERE t1.contype = 'p' AND length(t3.attname) > 0 AND t2.oid = '表名' :: regclass group by t4.tablename
目前隻找到瞭獲取指定表的主鍵信息,對於批量獲取沒有找到。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- PostgreSQL 查找當前數據庫的所有表操作
- PostgreSQL 實現查詢表字段信息SQL腳本
- pgsql 實現用戶自定義表結構信息獲取
- Postgresql 實現查詢一個表/所有表的所有列名
- 解析PostgreSQL中Oid和Relfilenode的映射問題