Reputation:
[db2-as400] I have a table ENR_DATA
that has column EnrollmentID
as a primary key. This column is referred by many tables as a "foreign key". Is there a way to list down all those tables who refer to EnrollmentID
of ENR_DATA
table?
Upvotes: 3
Views: 4327
Reputation: 11473
There are a few catalog views that each give just a part of the answer, and you have to join them all together.
From these three tables we can write the following SQL:
select cst.constraint_schema, cst.constraint_name,
fk.table_schema, fk.table_name, fk.ordinal_position, fk.column_name,
pk.table_schema, pk.table_name, pk.column_name
from qsys2.syscst cst
join qsys2.syskeycst fk
on fk.constraint_schema = cst.constraint_schema
and fk.constraint_name = cst.constraint_name
join qsys2.sysrefcst ref
on ref.constraint_schema = cst.constraint_schema
and ref.constraint_name = cst.constraint_name
join qsys2.syskeycst pk
on pk.constraint_schema = ref.unique_constraint_schema
and pk.constraint_name = ref.unique_constraint_name
where cst.constraint_type = 'FOREIGN KEY'
and fk.ordinal_position = pk.ordinal_position
and pk.table_name = 'ENR_DATA'
and pk.column_name = 'ENROLLMENTID'
order by cst.constraint_schema, cst.constraint_name;
This will get you the table names that reference 'ENR_DATA' via foreign key. Note I have ENROLLMENTID in all upper case. That is how DB2 for i stores all column names unless they are quoted using "".
Upvotes: 5
Reputation: 17118
DB2 on IBM i (AS 400) offers a list of all system tables, the system catalog. It is the place where metadata is stored. One of the views, SYSCST, is the view with all constraints, the view SYSCSTCOL has information about the constraint columns, and SYSCSTDEP stores the dependencies.
So you would query SYSCST, SYSCSTCOL and SYSCSTDEP for finding the details.
Upvotes: 0