0

我有一个表实体。该表引用了各种查找表。例如,实体表中的字段“ethnicity_code”引用了一个名为“lkp_race”的查找表。现在要弄清楚种族和民族之间的联系并不难,但在她的例子中,这种联系并不那么清楚。我希望能够知道哪些“lkp_”表是从其他表(如实体)中引用的。有没有办法使用 Oracle pl sql 编写查询来表示如下内容:

如果 tablename LIKE 'lkp_%' 那么链接到这些表的表是什么以及它们链接到哪些字段?

那有意义吗?

4

3 回答 3

1

您可以查询USER_CONSTRAINTS以获取外键引用。寻找“R”类型的约束(参考):

SELECT R_Constraint_Name
FROM User_Constraints
WHERE Table_Name = 'ENTITY'
  AND Constraint_Type = 'R'

这将为您提供ENTITY表引用的表中的主键列表。要获取引用的表名有点混乱:您需要自联接到USER_CONSTRAINTS表:

SELECT target.Table_Name
FROM User_Constraints src
JOIN User_Constraints target ON src.R_Constraint_Name = target.Constraint_Name
WHERE src.Table_Name = 'ENTITY'
  AND src.Constraint_Type = 'R'

要列出另一个表中引用的列,请使用User_Cons_Columns视图:

SELECT cols.Table_Name, cols.Column_Name
FROM User_Constraints src
JOIN User_Cons_Columns cols ON src.R_Constraint_Name = cols.Constraint_Name
WHERE src.Table_Name = 'ENTITY'
  AND src.Constraint_Type = 'R'
ORDER BY src.Table_Name, cols.Position
于 2013-09-17T14:54:21.933 回答
0

试试这个查询:

CREATE TABLE entity(
  somefield varchar2(100),
  ethnicity_code number
);

CREATE TABLE lkp_race(
  code number primary key,
  some_other_field varchar2( 100)
);

ALTER TABLE entity ADD CONSTRAINT eth_code_fk
   FOREIGN KEY ( ethnicity_code ) REFERENCES lkp_race( code );

  SELECT x1.table_name,
          col1.column_name,
          x2.table_name referenced_table_name,
          col2.column_name referenced_column_name
   FROM  all_constraints x1
   JOIN all_constraints x2
   ON x1.constraint_name = x2.r_constraint_name
   JOIN all_cons_columns col1
   ON x1.constraint_name = col1.constraint_name 
      AND x1.table_name = col1.table_name
   JOIN all_cons_columns col2
   ON x2.constraint_name = col2.constraint_name 
      AND x2.table_name = col2.table_name
   WHERE x1.owner = 'TEST' 
     AND x1.table_name LIKE 'LKP%'
   ORDER BY x1.owner, x1.table_name, col1.position,
            x2.owner, x2.table_name, col2.position;

结果:

TABLE_NAME COLUMN_NAME REFERENCED_TABLE_NAME REFERENCED_COLUMN_NAME
---------- ----------- --------------------- ----------------------
LKP_RACE   CODE        ENTITY                ETHNICITY_CODE     
于 2013-09-17T15:31:49.423 回答
0
SELECT f.name AS ForeignKey,
SCHEMA_NAME(f.SCHEMA_ID) SchemaName,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,
SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
order by 1;
于 2016-04-15T07:10:04.620 回答