sql – 使用表,字段和模式名称查找引用的表名

我有一个要求,我需要通过表中的特定字段(外键表)使用此字段名称,表名(此字段所在的位置)和模式名称(其中)查找引用的表名(主键表名)桌子,因此场地居住)

例如:

Schema1.TableA
  Id (Integer,PK)  
  Name varchar


Schema2.TableB
  Id (integer,PK)  
  A_Id (integer,FK referencing TableA.Id)  
  Name varchar

我需要将A_Id,TableB和Schema2传递给函数获取Schema1.TableA作为结果.

我正在使用Postgres 8.3.

解决方法

如果您不需要将其移植到另一个RDBMS,那么在pg_catalog中使用目录表而不是标准信息模式会更快更简单:
SELECT c.confrelid::regclass::text AS referenced_table,c.conname AS fk_name,pg_get_constraintdef(c.oid) AS fk_deFinition
FROM   pg_attribute a 
JOIN   pg_constraint c ON (c.conrelid,c.conkey[1]) = (a.attrelid,a.attnum)
WHERE  a.attrelid = '"Schema2"."TableB"'::regclass   -- table name
AND    a.attname  = 'A_Id'                           -- column name  
AND    c.contype  = 'f'
ORDER  BY conrelid::regclass::text,contype DESC;

返回:

referenced_table | fk_name  |  fk_deFinition
------------------+-------------------------+----------------------------------------------
 Schema1.TableA   | b1_fkey  | FOREIGN KEY ("B_id") REFERENCES "Schema1"."TableA"("A_id")

笔记

>另外两列仅用于定向.根据你的Q,你只需要第一列.
>这将返回涉及给定列名的所有外键的所有引用表 – 包括多列上的FK约束.
>根据当前search_path设置的可见性,名称自动进行模式限定.该名称也会在需要时自动转义(非法或大写字符,保留字,…).

查看手册中的pg_constraintpg_attribute的详细信息.还有更多关于object identifier types.

有关:

> PostgreSQL drop constraint with unknown name
> Retrieving all PK and FK

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...