views:

669

answers:

3

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

+5  A: 
ALTER TABLE tGeoAnswers ADD CONSTRAINT FK_Answer_Location ...

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

Bill Karwin
A: 

Please have a look at the bottom of http://www.1keydata.com/sql/sql-foreign-key.html about the ALTER TABLE ADD ... FOREIGN KEY syntax.

pts
+1  A: 

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

 ALTER TABLE tGeoAnswers
 ADD CONSTRAINT FK_Answer_Location
 FOREIGN KEY (LocationId) REFERENCES tLocation (Id)
Mark Brackett