Create Foreign Key SQL

▼魔方 西西 提交于 2020-01-02 10:28:12

问题


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


回答1:


ALTER TABLE tGeoAnswers ADD CONSTRAINT FK_Answer_Location ...

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




回答2:


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

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



回答3:


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.



来源:https://stackoverflow.com/questions/842151/create-foreign-key-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!