Articles → SQL SERVER → Constraints In SQL Server

Constraints In SQL Server






What Is A Constraint?





Primary Key Constraint




  1. Contains unique value
  2. It should not be null



Example




Create table Test (
  PK_ID int, 
  sName varchar(100), 
  Primary key (PK_ID)
)




insert into Test values(1,'hi')




insert into Test values(1,'hi')











Apply Primary Key Constraint To The Existing Table




ALTER TABLE Test Add Primary key (PK_ID)






Create table Test (
  PK_ID int not null, 
  sName varchar(100)
)



Foreign Key Constraint










-- Person 
Create table Person (
  PersonID int, 
  FullName varchar(100), 
  CityID int, 
  Primary key (PersonID), 
  Foreign key (CityID) References City (CityID)
) 
-- City
Create table City (
  CityID int, 
  City varchar(50), 
  primary key (CityID)
)






Foreign key (CityID) References City (CityID)




insert into City values(1,'Gurgaon')




CityIDCity
1Gurgaon




insert into Person values('karan Gupta',1)




PersonIDFullNameCityID
1Karan Gupta1




insert into Person values('karan',2)













Posted By  -  Karan Gupta
 
Posted On  -  Monday, March 15, 2010

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250