Monday, September 9, 2013

SQL Server - How to create/make Foreign Key on the table object.

     Most of the time many new SQL developer do not able to create the primary key and Foreign Key relationship. In this post I am going to show this steps and it very simple to understand.

We have to create to table first for Primary Key and second for Foreign Key.
--Step1- First table creating here. With Primary Key on RuleID column.

create TABLE dbo.Table1_Rule
RuleID int primary key,
Rulename varchar(50),
Status bit ,
Createdate datetime,
Castupdate datetime

-    Step2 - Now we are creating second table with  getting reference for Foreign Key.

create  TABLE dbo.Table2_Condition

RuleConditionID int ,
RuleID int references dbo.Table1_Rule(RuleID ),
AppliedContent bit ,
Operation varchar(50),
value varchar(50)

--Step 3 - Then we are appling Foreign Key in second(dbo.Table2_Condition) table on RuleID column.

ALTER TABLE dbo.Table2_Condition

Like and Share to SQL Integrity Blog