Defines a foreign key on a table or view in the current database.


sp_foreignkey tabname, pktabname, col1 [, col2] ... 
	[, col8] 



is the name of the table or view that contains the foreign key to be defined.


is the name of the table or view that has the primary key to which the foreign key applies. The primary key must already be defined.


is the name of the first column that makes up the foreign key. The foreign key must have at least one column and can have a maximum of eight columns.


Example 1

The primary key of the publishers table is the pub_id column. The titles table also contains a pub_id column, which is a foreign key of publishers:

sp_foreignkey titles, publishers, pub_id

Example 2

The primary key of the parts table has been defined with sp_primarykey as the partnumber and subpartnumber columns. The orders table contains the columns part and subpart, which make up a foreign key of parts:

sp_foreignkey orders, parts, part, subpart



Only the owner of the table or view can execute sp_foreignkey.

See also

Commands alter table, create table, create trigger

System procedures sp_commonkey, sp_dropkey, sp_helpjoins, sp_helpkey, sp_primarykey