|
I see this listed in article all the time. What does it mean to have a foreign key and how do I set one up in SQL Server?
(comments are locked)
|
|
A Foreign Key (FK) in a SQL table’s field refers to a look-up (reference) field in another table. A simple example: dbo.tblCustomers has a field name “StateID”. One would probably make this field a Foreign Key (FK) so that it would only take entries from a specific table’s specific field (e.g. dbo.tblLIBStates field name “StateID”). FK ensures correctness of data (e.g naming conventions, etc) in the primary table.
(comments are locked)
|
|
A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity of the data. A foreign key can reference any candidate key. The target of a foreign key doesn't have to be the primary key. It could also be in the same table - it doesn't have to be in another table. Additionally, SQL Server will let you create a FOREIGN KEY constraint that matches the column list of any unique index.
Oct 30 '09 at 09:46 AM
David 1
I should have used a broader and more correct term for the purpose of FK "i.e. referential integrity of the data" in my posting. Thank you for pointing this out, Nitin.
Oct 30 '09 at 11:10 AM
Mansour Shoari
(comments are locked)
|
|
For completeness: A foreign key is a reference from a value or set of values in one table, to a value or set of values in a 'target' or 'referenced' table, which can be a different table or the same table as the 'primary' or 'parent' table. The target value set must be NON-NULLABLE, and enforced unique through either a PRIMARY KEY constraint, a UNIQUE constraint or a UNIQUE INDEX. Foreign keys can be enabled or disabled, although disabling foreign keys can sometimes cause the query optimiser to make incorrect assumptions about the presence of data in the target table in older versions of SQL Server. Foreign keys also have referential actions which are invokes when a row in a target table that is referenced by a row in the primary table is deleted, or any of the values in the set of values are updated. These actions are:
Foreign keys can also be marked as 'NOT FOR REPLICATION' which means that the constraint is not enforced when replication agents perform operations on the data. The MSDN reference to the
(comments are locked)
|

