I am new to oracle, I am working on tables where I need to fetch constraints between 2 tables and send the values as another input.
Table 1
|_ Column1_pk
|_ Column2 (foreign key to Table 2)
Table 2
|_column2
So I want to fetch primary key of table1 and column which have the relation between 2 tables
You need to query the dictionary views USER_CONSTRAINTS
and USER_CONS_COLUMNS
. For example:
Table DEPT
has a primary key, and table EMP
has a foreign key pointing to DEPT
. First we find the constraint name, and then the column(s), of the primary key of DEPT
. Then, with the constraint name in hand, we find the constraint name, and then the column(s), for the foreign key of EMP
.
select table_name, constraint_name, constraint_type
from user_constraints
where table_name = 'DEPT'
and constraint_type = 'P'
;
TABLE_NAME CONSTRAINT_NAME CONSTRAINT_TYPE
---------- --------------- ---------------
DEPT PK_DEPT P
select constraint_name, table_name, column_name, position
from user_cons_columns
where constraint_name = 'PK_DEPT'
;
CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION
--------------- ---------- ----------- --------
PK_DEPT DEPT DEPTNO 1
and then
select table_name, constraint_name, constraint_type
from user_constraints
where table_name = 'EMP'
and r_constraint_name = 'PK_DEPT'
;
TABLE_NAME CONSTRAINT_NAME CONSTRAINT_TYPE
---------- --------------- ---------------
EMP FK_DEPTNO R
select constraint_name, table_name, column_name, position
from user_cons_columns
where constraint_name = 'FK_DEPTNO'
;
CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION
--------------- ---------- ----------- --------
FK_DEPTNO EMP DEPTNO 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.