Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Foreign Key SQL

How do I create a foreign key

from table tGeoAnswers column 'locationId'

to table tLocations column 'id'?

ALTER TABLE 
        tGeoAnswers 
ADD 
        FK_Answer_Location 
FOREIGN KEY 
        (locationId)
REFERENCES 
        tLocations(id)

I am trying this code that I found but I get the following error:

The definition for column 'FK_Answer_Location' must include a data type

like image 998
Bryan Avatar asked Feb 12 '26 03:02

Bryan


2 Answers

ALTER TABLE tGeoAnswers ADD CONSTRAINT FK_Answer_Location ...

Otherwise it assumes you're adding a column called FK_Answer_Location.

like image 75
Bill Karwin Avatar answered Feb 15 '26 10:02

Bill Karwin


Assuming MsSql Server/T-SQL, use ALTER TABLE:

 ALTER TABLE tGeoAnswers
 ADD CONSTRAINT FK_Answer_Location
 FOREIGN KEY (LocationId) REFERENCES tLocation (Id)
like image 34
Mark Brackett Avatar answered Feb 15 '26 11:02

Mark Brackett