Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Sql Server Query to Find All Foreign Keys References of Particular Table

$
0
0

Introduction : In this article I have explained How to get all foreign key reference of any particular table with full details i.e. referenced table with schema, referring table with schema, referenced column, referring column, foreign key constraint name in sql server. I.e. listing all child tables containing primary key column of parent table as a foreign key.

In previous articles i explained the Difference between primary key and foreign key in sql server and Find al lprimary and foreign key constraints on each or any table in database and Drop or truncate parent table by dropping all foreign key constraints and Declare and use table variables in sql server and Multiple sqlqueries to find all user defined functions (udf’s) in a database

Implementation : Lets create a parent table 'tbEmployee' having Primary Key column 'EmployeeId' and two child tables 'tbEmployeeExperience' and 'tbEmployeeQualification' having EmployeeId as foreign key as.

-- Create a parent table using following script

CREATE TABLE tbEmployee ( EmployeeId INT IDENTITY ( 1 , 1 ) NOT NULL PRIMARY KEY , EmployeeName VARCHAR ( 100 ) ); GO -- Create a child table that refer above parent table 'tbEmployee' using following script CREATE TABLE tbEmployeeExperience ( CompanyName VARCHAR ( 200 ), TotalMonths INT , EmployeeId INT FOREIGN KEY REFERENCES tbEmployee ( EmployeeId ), ); GO -- Create another child table that refer above parent table 'tbEmployee' using following script CREATE TABLE tbEmployeQualification ( QualificationName VARCHAR ( 200 ), EmployeeId INT FOREIGN KEY REFERENCES tbEmployee ( EmployeeId ), ); Query to find all foreign keys reference of particular table SELECT SCM . name [Schema] , OBJECT_NAME ( FK . referenced_object_id ) 'Referenced Table' , COL_NAME ( FK . referenced_object_id , FKC . referenced_column_id ) 'Referenced Column' , SCM . name [Schema] , OBJECT_NAME ( FK . parent_object_id ) 'Referring Table' , COL_NAME ( FK . parent_object_id , FKC . parent_column_id ) 'Referring Column' , FK . name 'Foreign Key Name' FROM sys . foreign_keys AS FK INNER JOIN sys . foreign_key_columns AS FKC ON FKC . constraint_object_id = FK . object_id INNER JOIN sys . schemas SCM ON FK . schema_id = SCM . schema_id WHERE FK . referenced_object_id = OBJECT_ID ( 'dbo.tbEmployee' )

Result:

Schema Referenced Table Referenced Column Schema Referring Table

Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles