![]() |
Foreign Keys |
|
Introduction |
To create a foreign key in the SQL, the basic formula to use is:
FOREIGN KEY REFERENCES ParentTableName(ForeignKeyCcolumn)
Here is an example:
CREATE TABLE Persons
(
PersonID int identity(1,1) PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int NULL FOREIGN KEY REFERENCES Genders(GenderID)
);
|
A Constraint on a Foreign Key |
To create a foreign key as a constraint, use the CONSTRAINT keyword followed by the desired name and continue the rest as we saw above. Her is an example:
CREATE TABLE Persons
(
PersonID int identity(1,1) PRIMARY KEY NOT NULL,
FirstName nvarchar(20),
LastName nvarchar(20) NOT NULL,
GenderID int NULL CONSTRAINT FKGenders
FOREIGN KEY REFERENCES Genders(GenderID)
);
|
|
||
| Home | Copyright © 2007-2011 FunctionX.com, Inc. | |
|
|
||