SQL server creates “INFORMATION_SCHEMA“ views for retrieviing metadata about the objects within a database.

  1. CREATE DATABASE DB_INFORMATION_SCHEMA_VIEW
  2. GO
  3. USE DB_INFORMATION_SCHEMA_VIEW
  4. GO
  5. CREATE TABLE tbl_parent
  6. (
  7. Id INT IDENTITY(1,1) CONSTRAINT PK_tbl_parent_Id PRIMARY KEY,
  8. Name VARCHAR(50)
  9. )
  10. GO
  11. CREATE TABLE tbl_child
  12. (
  13. Id INT IDENTITY(1,1) PRIMARY KEY,
  14. Name VARCHAR(50),
  15. ParentId INT CONSTRAINT FK_tbl_parent_tbl_child_ParentId FOREIGN KEY REFERENCES tbl_parent(Id)
  16. )
  17. GO
If we want to know the table’s primary keys and foreign keys.

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.
  1. USE DB_INFORMATION_SCHEMA_VIEW
  2. GO
  3. SELECT * FROM information_schema.key_column_usage
  4. --WHERE table_name = 'tbl_child'
  5. GO
query output

<< SQL Server: System Views