We can use script like below to identify whether a Table is referenced by another Tables foreign key constraints in Sql Server:
ALSO READ: How to find all dependencies of a table in Sql Server?
SELECT OBJECT_NAME (FK.referenced_object_id) 'Referenced Table', OBJECT_NAME(FK.parent_object_id) 'Referring Table', FK.name 'Foreign Key', COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) 'Referenced Column', COL_NAME(FK.parent_object_id,FKC.parent_column_id) 'Referring Column' FROM sys.foreign_keys AS FK INNER JOIN sys.foreign_key_columns AS FKC ON FKC.constraint_object_id = FK.OBJECT_ID WHERE OBJECT_NAME (FK.referenced_object_id) = 'Enter Table Name'
Let us understand this with an example:
Below script creates a database SqlHintsDemo and adds to tables Customer and Order to it. Here foreign key constraints FK_Order_Customer defined on the Order Table CustID column refers to the CustomerId column of the Customer table.
CREATE DATABASE SqlHintsDemo GO USE SqlHintsDemo GO CREATE TABLE [dbo].[Customer] ( [CustomerId] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY CLUSTERED) GO CREATE TABLE [dbo].[Order] ( [OrderID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY CLUSTERED , [CustID] [int] NOT NULL , CONSTRAINT [FK_Order_Customer] FOREIGN KEY ([CustID]) REFERENCES [dbo].[Customer] ([CustomerId]) ) GO
We can use a script like below to identify whether the Customer Table is referred by any other Tables foreign key constraint:
SELECT OBJECT_NAME (FK.referenced_object_id) 'Referenced Table', OBJECT_NAME(FK.parent_object_id) 'Referring Table', FK.name 'Foreign Key', COL_NAME(FK.referenced_object_id, FKC.referenced_column_id) 'Referenced Column', COL_NAME(FK.parent_object_id,FKC.parent_column_id) 'Referring Column' FROM sys.foreign_keys AS FK INNER JOIN sys.foreign_key_columns AS FKC ON FKC.constraint_object_id = FK.OBJECT_ID WHERE OBJECT_NAME (FK.referenced_object_id) = 'Customer'
hai ……… nice blog thanks
how can i find FK is coonected to which table and it is poosible that my table can be in another server