首页 > 代码库 > SQL - Create Foreign Key Relationships

SQL - Create Foreign Key Relationships

/* To create a foreign key in a new table */
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
);
GO
/* To create a foreign key in an existing table */
ALTER TABLE Sales.TempSalesReason
	ADD CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID)
		REFERENCES Sales.SalesReason (SalesReasonID)
		ON DELETE CASCADE
		ON UPDATE CASCADE
;
GO

SQL - Create Foreign Key Relationships