有谁知道如何在Postgres 9.1中找到表的OID?我正在编写一个更新脚本,需要在尝试创建列之前测试表中是否存在列 . 这是为了防止脚本在第一次出错后运行 .
postgres目录表 pg_class 是你应该看到的 . 每个表应该有一行,表名在 relname 列中,而oid在隐藏列 oid 中 .
pg_class
relname
oid
目录表位于 postgres 数据库中,因此请确保连接到该数据库,而不是应用程序数据库 .
postgres
您可能还对 pg_attribute 目录表感兴趣,该表包含每个表列一行 .
pg_attribute
见:http://www.postgresql.org/docs/current/static/catalog-pg-class.html和http://www.postgresql.org/docs/current/static/catalog-pg-attribute.html
要获取表OID,请转换为object identifier type regclass (同时连接到同一个DB):
regclass
SELECT 'mytbl'::regclass::oid;
这将在search_path找到具有给定名称的第一个表(或视图等),或者如果未找到则引发异常 .
模式限定表名以删除对搜索路径的依赖:
SELECT 'myschema.mytbl'::regclass::oid;
在Postgres 9.4 或更高版本中,您还可以使用 to_regclass('myschema.mytbl') ,如果找不到表,则不会引发异常:
to_regclass('myschema.mytbl')
然后,您只需查询目录表pg_attribute是否存在该列:
SELECT TRUE AS col_exists FROM pg_attribute WHERE attrelid = 'myschema.mytbl'::regclass AND attname = 'mycol' AND NOT attisdropped -- no dropped (dead) columns -- AND attnum > 0 -- no system columns (you may or may not want this)
只是为了完成我想要添加的可能性,存在一种删除列的语法,以便不会出错:
ALTER TABLE mytbl DROP COLUMN如果EXISTS mycol
见http://www.postgresql.org/docs/9.0/static/sql-altertable.html
然后,您可以安全地添加列 .
SELECT oid FROM pg_class WHERE relname = 'tbl_name' AND relkind = 'r';
4 回答
postgres目录表
pg_class
是你应该看到的 . 每个表应该有一行,表名在relname
列中,而oid在隐藏列oid
中 .目录表位于
postgres
数据库中,因此请确保连接到该数据库,而不是应用程序数据库 .您可能还对
pg_attribute
目录表感兴趣,该表包含每个表列一行 .见:http://www.postgresql.org/docs/current/static/catalog-pg-class.html和http://www.postgresql.org/docs/current/static/catalog-pg-attribute.html
要获取表OID,请转换为object identifier type
regclass
(同时连接到同一个DB):这将在search_path找到具有给定名称的第一个表(或视图等),或者如果未找到则引发异常 .
模式限定表名以删除对搜索路径的依赖:
在Postgres 9.4 或更高版本中,您还可以使用
to_regclass('myschema.mytbl')
,如果找不到表,则不会引发异常:然后,您只需查询目录表pg_attribute是否存在该列:
只是为了完成我想要添加的可能性,存在一种删除列的语法,以便不会出错:
ALTER TABLE mytbl DROP COLUMN如果EXISTS mycol
见http://www.postgresql.org/docs/9.0/static/sql-altertable.html
然后,您可以安全地添加列 .