Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 About Foreign Key Constraint

Author  Topic 

zhshqzyc
Posting Yak Master

240 Posts

Posted - 2013-03-08 : 13:46:37
http://www.w3schools.com/sql/sql_foreignkey.asp
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:


ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)


To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

One has the keyword "constraint", the other no.
I can't figure it out the difference.
I think that the first one is enough for the normal query.

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2013-03-08 : 19:38:56
Question: Do you want to define the name of the constraint? (Hint: You do!)
Use the syntax that allows you to do what you want. Also, it is common practice to also define an index on the foreign key column(s) for performance purposes. You may already have this in place or your tables may be too small to warrant it.

=================================================
There are two kinds of light -- the glow that illuminates, and the glare that obscures. -James Thurber
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-03-09 : 00:55:34
defining it as a constraint makes it easier to identify it later

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -