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.html和http://www.postgresql.org/docs/current/static/catalog-pg-attribute.html
SELECT oid FROM pg_class WHERE relname = 'tbl_name' AND relkind = 'r';
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33317 次 |
最近记录: |