How to Find Tables with Primary or Foreign Key in SQL Server Management Studio

0
7805

If you want to know if a table has a primary key or foreign key, you can find out this in many ways. Today, we mainly talk about how to do it using Management Studio. Now, connect to SQL Server via Management studio and do the following steps.

Let us create these tables:

CREATE TABLE Skills (

ID INTEGER PRIMARY KEY,

SkillName CHAR(40),

Description CHAR(100)

)

Go

CREATE TABLE EmployeeSkills2 (

EmployeeID INTEGER NOT NULL,

SkillID INTEGER NOT NULL,

SkillLevel INTEGER NOT NULL,

PRIMARY KEY( EmployeeID ),

)

GO

Find Tables with Primary or Foreign Key in SQL Server Management Studio 1

Now let us create foreign key:

ALTER TABLE EmployeeSkills2

ADD CONSTRAINT  Skill_FK  FOREIGN KEY( SkillID )

REFERENCES Skills ( ID );

Find Tables with Primary or Foreign Key in SQL Server Management Studio 2

Now if you want to check if a table has a primary key, you can use the following methods.

(1)Use sp_pkeys system stored procedure.

EXEC sp_PKEYS Skills

The result is :

Find Tables with Primary or Foreign Key in SQL Server Management Studio 3

(2)Use SQL Server xtype function

Find Tables with Primary or Foreign Key in SQL Server Management Studio 4

If you want to check if a table has a foreign key, you can use the following method.

Find Tables with Primary or Foreign Key in SQL Server Management Studio 5