Script all Primary Keys, Foreign Keys in a SQL Server using T-SQL

Script all Primary Keys, Foreign Keys in a SQL Server using T-SQL

Find the relationships between tables in sql server
Get Primary Key and Foreign Key details using T-SQL
 
How to find all related tables of a given table?
You got a new database and you started working on that. Essentially when times we have to work with a new database first we need to understand the table structure and relationships. The overall structure we can understand from schema / entity diagrams.
But when it is time to start developing sql code on new database it would always be an easier way to find dependent objects of a given table using “sp_help” or with “Alt+F1”.
Here with I am giving one more way which is handy to find out these details.

When we need to Script all Primary Keys and Foreign Keys in SQL Server:

  1. When we need to understand a database system
  2. Data Imports / Delete / Truncate
  3. While moving code between environment
Now we will see the script to list out all primary and foreign keys in sql server using t-sql

Have a look at the stored procedure “[usp_get_related_Tables]” below.

 

To know relationship (Primary key/ Foreign Key) details for all tables

EXEC [dbo].[usp_get_related_Tables]

To know relationship (Primary key/ Foreign Key) details for all tables under a given schema “Sales”

To know relationship (Primary key/ Foreign Key) details for a given Table “Employee”

 
This Procedure was tested on SQL Server 2005, 2008 and on 2008R2.
 
 
Posted in SQL Development, SQL Scripts | Tagged , , , , , , | Leave a comment

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz