SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 About Foreign Key Constraint
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

zhshqzyc
Posting Yak Master

240 Posts

Posted - 03/08/2013 :  13:46:37  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

USA
1643 Posts

Posted - 03/08/2013 :  19:38:56  Show Profile  Reply with Quote
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

India
52309 Posts

Posted - 03/09/2013 :  00:55:34  Show Profile  Reply with Quote
defining it as a constraint makes it easier to identify it later

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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000