SQL server creates “INFORMATION_SCHEMA“ views for retrieviing metadata about the objects within a database.
- CREATE DATABASE DB_INFORMATION_SCHEMA_VIEW
- GO
- USE DB_INFORMATION_SCHEMA_VIEW
- GO
- CREATE TABLE tbl_parent
- (
- Id INT IDENTITY(1,1) CONSTRAINT PK_tbl_parent_Id PRIMARY KEY,
- Name VARCHAR(50)
- )
- GO
- CREATE TABLE tbl_child
- (
- Id INT IDENTITY(1,1) PRIMARY KEY,
- Name VARCHAR(50),
- ParentId INT CONSTRAINT FK_tbl_parent_tbl_child_ParentId FOREIGN KEY REFERENCES tbl_parent(Id)
- )
- GO
We can simply use an “information_schema.key_column_usage” view, this view will return all of the table's foreign keys and primary keys.
- USE DB_INFORMATION_SCHEMA_VIEW
- GO
- SELECT * FROM information_schema.key_column_usage
- --WHERE table_name = 'tbl_child'
- GO

<< SQL Server: System Views

Join the conversation! Your thoughts help the community grow.