Add a foreign key constraint on the existing table – SQL Server

While it is best to create and build the link between tables before the data flow begins, new tables or other existing tables may need to be linked due to a change in plans.

In such scenarios using ALTER statement, foreign keys can be created as shown below.

ALTER TABLE tbOrderDetails
ADD CONSTRAINT FK_OrderID_tbOrderDetails FOREIGN KEY (OrderID)
REFERENCES tbOrders (OrderID)
ON DELETE CASCADE
ON UPDATE CASCADE
;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s