Here are the 3 different ways to add a Foreign Key in an existing table:-
- By using ADD CONSTRAINT with update and delete cascade command:-
ALTER TABLE dbo.State
ADD CONSTRAINT fk_city_id
FOREIGN KEY (CityID)
REFERENCES
City (CityID)
ON UPDATE CASCADE
ON DELETE CASCADE;
In this query update cascade will update the column when referenced column is updated and delete cascade will delete the row when data in the referenced column is deleted.
In this query update cascade will update the column when referenced column is updated and delete cascade will delete the row when data in the referenced column is deleted.
2. By using ADD column name along with constraint
Alter table dbo.State
Alter table dbo.State
ADD CityID
int CONSTRAINT fk_city_id FOREIGN KEY REFERENCES City (CityID)
3. By using ADD CONSTRAINT without cascade
Alter table dbo.State
ADD CONSTRAINT
fk_city_id FOREIGN
KEY(CityID) REFERENCES City (CityID)
Sign up here with your email
Conversion Conversion Emoticon Emoticon