Code Snippet posted by: Abhisek
| Posted on: 11/30/2009 | Category: SQL Server Codes
| Views: 1466 | Status: [Member]
| Alert Moderator
The following syntax is used to add a foreign key to an existing table in the database,
ALTER TABLE<table_name>ADD CONSTRAINTS<cons_name> FOREIGN KEY(col_name)REFERENCES pk_table(col_name)
is the name of the table which will be accessed by the foreign key and that contains the primary key. col_name
is the name of the column on which primary key is defined in the primary table.
When a foreign key is added to an existing table, Microsoft SQL Server 2000 by default checks the existing data in the columns to ensure that all values except null, exists in the columns of the refereed primary key.
However SQL Server can be prevented from checking the data in the column against the new constraints and made to add the new constraint regardless of data in the column. This option is useful when the rule requires the constraints to be enforced only from this point forward.