Scenario:You have created two tables dbo.Customer and dbo.Orders without having primary-foreign key relationship. After creating tables you inserted few records. Later you realized that you were supposed to add Foreign Key Constraint. When you tried to alter dbo.Orders table , you received error.
Create dbo.Customer and Dbo.Order Tables by using below script
USE YourDatabaseName GO CREATE TABLE dbo.Customer ( Customerid INT PRIMARY KEY ,FName VARCHAR(100) ,LName VARCHAR(100) ,SSN VARCHAR(10) ) CREATE TABLE dbo.Orders ( OrderId INT Identity(1, 1) ,OrderitemName VARCHAR(50) ,OrderItemAmt INT, CustomerId int )Insert sample records by using below script.
INSERT INTO dbo.Customer (CustomerId,FName, LName,SSN) VALUES (1,'Aamir','Shahzad','000-000-00') INSERT INTO dbo.Orders (OrderItemName,OrderItemAmt,Customerid) values ('TV',2,2)Now let's add Foreign Key Constraint
Alter table dbo.Orders Add Constraint Fk_CustomerId Foreign Key(CustomerId) References dbo.Customer(CustomerId)When we execute above script, we get below error.
Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "Fk_CustomerId". The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'Customerid'.
Alter table dbo.Orders with Nocheck Add Constraint Fk_CustomerId Foreign Key(CustomerId) References dbo.Customer(CustomerId)