Adding foreign key to an existing table

Posted by Abhisek under Sql Server category on | Views : 2372
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)

pk_table 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.

Comments or Responses

Login to post response