foreign key constraint in ms sql code example
Example 1: sql server foreign key
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
Example 2: foreign key mssql
CREATE TABLE Sales.TempSalesReason
(
TempID int NOT NULL, Name nvarchar(50)
, CONSTRAINT PK_TempSales PRIMARY KEY NONCLUSTERED (TempID)
, CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
REFERENCES Sales.SalesReason (SalesReasonID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
;
Example 3: foreign key constraint in ms sql
ALTER TABLE ForeignKeyTable ADD CONSTRAINT ForeignKeyTable_foreignKeyColumn_FK
FOREIGN KEY (foreignKeyColumn) REFERENCES PrimaryKeyTable (PrimaryKeyColumn)
Example 4: sql server foreign key
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);