I have one table Called Member
with Column Name Member_Id
.
This Table Referred by more than 23 other tables as Primary Table with Member_Id
as Foreign Column.
Now these 23 tables also have Primary Keys, and some serve also as Primary table for other tables.
So I want to fetch all Foreign Keys for all dependent Table referring to table Member
.
My Goal is to Truncate Member
table which has Foreign keys. I can't use Delete as these tables have more data, so it may take ages for me to delete the data.
For Example:-
Member --> Member-ID
Member-Contact
connect with Member
table Using Member_ID, Primary Key Contact_No
Member_Population
connect with Member
table Using Member_ID, Primary Key population_seq_no
...23 More
These Member-Contact
, Member_Population
and 23 more also have dependent tables with other tables as Foreign Keys.
So before truncate I need to Drop All Foreign Keys then Truncate All these dependent tables then Restore these foreign keys.
Till now I write this query which fetch all Foreign Keys for one table
SELECT ROW_NUMBER() Over(Order BY f.parent_object_id) as RowID,
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName,
f.name as FKConstraintName,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) as ReferenceColName
--INTO #temp_ReferenceContstraints
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.tables t ON t.OBJECT_ID = fc.referenced_object_id
WHERE OBJECT_NAME (f.referenced_object_id) = 'Member'
I want to find all foreign keys for all dependent tables?