Oct 21, 2014

FOREIGN KEY constraint in sql server

FOREIGN KEY- This constraints responsible to uniquely identified a rows or records to another table.

Example-

Following table structure can clear your concept of foreign key constraint.

Product Table

CREATE TABLE PRODUCT
(
ID INT NOT NULL IDENTITY(1,1),
SKU VARCHAR(20) NOT NULL,
TITLE VARCHAR(200) NOT NULL,
PRICE MONEY NOT NULL,
DISCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME NULL
CONSTRAINT pk_ID PRIMARY KEY (ID)
)

Product Order Table

CREATE TABLE PRODUCT_IMAGE
(
ID INT NOT NULL IDENTITY(1,1),
PRODUCT_ID INT NOT NULL REFERENCES PRODUCT(ID),
IMGURL VARCHAR(200) NOT NULL ,
DTCREATE DATETIME
)

To create foreign key constraint to existing table use following query.

ALTER TABLE PRODUCT_IMAGE ADD FOREIGN KEY (PRODUCT_IDREFERENCESPRODUCT(ID)