在Postgres 9.1中确定表的OID?

Ton*_*ile 31 postgresql postgresql-9.1

有谁知道如何在Postgres 9.1中找到表的OID?我正在编写一个更新脚本,需要在尝试创建列之前测试表中是否存在列.这是为了防止脚本在第一次出错后运行.

Erw*_*ter 43

要获取表OID,请转换为对象标识符类型 regclass(连接到同一个DB时):

SELECT 'mytbl'::regclass::oid;
Run Code Online (Sandbox Code Playgroud)

这将查找具有给定名称的第一个表(或视图等),search_path如果未找到则引发异常.

模式限定表名以删除对搜索路径的依赖:

SELECT 'myschema.mytbl'::regclass::oid;
Run Code Online (Sandbox Code Playgroud)

在Postgres 9.4或更高版本中,您也可以使用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)
Run Code Online (Sandbox Code Playgroud)


小智 27

postgres目录表pg_class是你应该看到的.每个表应该有一行,表中的表名relname和隐藏列中的oid oid.

目录表位于postgres数据库中,因此请确保连接到该数据库,而不是应用程序数据库.

您可能还对pg_attribute目录表感兴趣,其中每个表列包含一行.

请参阅:http://www.postgresql.org/docs/current/static/catalog-pg-class.htmlhttp://www.postgresql.org/docs/current/static/catalog-pg-attribute.html

  • 这不太准确.每个数据库都有一个名为`pg_catalog`的模式,其中包含特定于数据库的目录表. (6认同)
  • 我看过关于“pg_class”和“pg_attribute”表的文档,但我不知道“pg_class”表中有一个名为“oid”的隐藏列。我无法从文档中找出 oid 的位置。谢谢! (2认同)

use*_*194 5

SELECT oid FROM pg_class WHERE relname = 'tbl_name' AND relkind = 'r';
Run Code Online (Sandbox Code Playgroud)