How to find the Name of the Primary Key in a table in SQL Server

1. Finding Primary Key Value Using SP_KEYS:

If you want to know the Primary Key Name in a table, the simplest and best method is to run the following query in SQL Server:

EXEC SP_PKEYS [Table_Name]
Example:
EXEC SP_PKEYS tblEmployee


Result:
The last column in the result shows the primary key name.

2. Finding Primary Key Value using SP_HELP:

You can use below query to find Primary Key in a table:
EXEC SP_HELP [Table_Name]
Example
EXEC SP_HELP tblEmployee

Result:
This command returns a lot of information about a table like Table Name and Owner, Column Names and Datatypes, Identity Column, Indexes, Primary Keys etc. The Primary Key Name is highlighted in the snap.

3. Find all the Primary Keys in a database:

If you are using SQL Server 2005 or higher, you can use below query to find all the Primary Keys in the Database:
SELECT * FROM sys.all_objects WHERE TYPE = 'PK'

Hope this post is useful. Get Dotnet Projects and Interview Questions at http://dotnetprojectninterviewquestions.blogspot.com/

0 comments:

Post a Comment

top