Tuesday, May 5, 2009

How to set Foreign key through sql script

Syntax:
ALTER TABLE TableName
ADD CONSTRAINT ConstraintName
FOREIGN KEY (ColumnInFirstTable)
REFERENCES ReferenceTable(ColumnName)

Example:
ALTER TABLE Employee
ADD CONSTRAINT Fk_Employee_AddressType
FOREIGN KEY (AddressTypeID)
REFERENCES AddressType (AddressTypeID)

Note: The column AddressTypeID should be a primary key in both tables.

No comments:

Post a Comment