2013-12-18 33 views
0

我有一個子表,說B哪些引用某些父表說A。現在,假設我在表B中有3個coulmns(例如:B1, B2,B3)。我寫了一個查詢來獲取表B中所有的約束條件如下:如何檢查特定的列引用父表

SELECT a.table_name, 
     a.column_name 
FROM ALL_CONS_COLUMNS A, ALL_CONSTRAINTS C 
where A.CONSTRAINT_NAME = C.CONSTRAINT_NAME 
    and a.table_name='B' 
    and C.CONSTRAINT_TYPE = 'C' 

結果:

Table Name Column Name 
B   B1 

現在我想知道,列B1引用到父表隨着列名稱也是如此。

回答

0

我正好有這個疑問躺在身邊:

SELECT 
FK_Table = FK.TABLE_NAME, 
FK_Column = CU.COLUMN_NAME, 
PK_Table = PK.TABLE_NAME, 
Constraint_Name = C.CONSTRAINT_NAME 
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
WHERE i1.CONSTRAINT_TYPE = 'FOREIGN KEY' 
) PT ON PT.TABLE_NAME = PK.TABLE_NAME 
---- optional: 
ORDER BY 
1,2,3,4 

應該做你想要什麼。

+0

編輯得到刪除多餘的列 –

+0

ORA-00923:在預期的位置找不到FROM關鍵字 00923. 00000 - 「在預期的位置找不到FROM關鍵字」 *原因: *操作: –

+0

確定。這個SQL是用於SQL Server的,絕對不會在Oracle中運行!而且你確實在它上面放了一個Oracle標籤,所以不要浪費你的時間... –

0

嘗試以下sql語句:

獲得母公司所有子表和列,

SELECT distinct confk.constraint_name, 
    confk.constraint_type, 
    confk.table_name child_table, 
    fkcon.column_name child_column, 
    conpk.table_name parent_table, 
    pkcon.column_name parent_column 
FROM dba_constraints confk, 
    dba_constraints conpk, 
    dba_cons_columns pkcon, 
    dba_cons_columns fkcon 
WHERE confk.r_constraint_name = conpk.constraint_name 
AND conpk.constraint_name  = pkcon.constraint_name 
AND confk.constraint_name  = fkcon.constraint_name 
AND confk.constraint_type  = 'R' 
AND pkcon.owner    = 'Your schema name' 
AND pkcon.table_name   ='your parent table name' 
AND pkcon.column_name   ='your parent column name'; 

獲取父表名和孩子的名字和列列,

SELECT distinct confk.constraint_name, 
    confk.constraint_type, 
    confk.table_name child_table, 
    fkcon.column_name child_column, 
    conpk.table_name parent_table, 
    pkcon.column_name parent_column 
FROM dba_constraints confk, 
    dba_constraints conpk, 
    dba_cons_columns pkcon, 
    dba_cons_columns fkcon 
WHERE confk.r_constraint_name = conpk.constraint_name 
AND conpk.constraint_name  = pkcon.constraint_name 
AND confk.constraint_name  = fkcon.constraint_name 
AND confk.constraint_type  = 'R' 
AND fkcon.owner    = 'Your schema name' 
AND fkcon.table_name   ='your child table name' 
AND fkcon.column_name   ='your child column name'; 
相關問題