Scenario:
You have already created two tables dbo.Customer and dbo.Orders. Primary Key is created on CustomerId column in dbo.Customer table.
USE YourDatabaseName
GO
CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)
CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
)
You need to alter dbo.Orders table and add Foreign key constraint for CustomerId from dbo.Customer.
Solution:
As the tables are already present, the below script can be used to alter dbo.Orders table and add Foreign Key constraint.
If the column already exists in second table on which you would like to create Foreign Key Constraint, you are good to run the below script. As we don't have the column in table, we are going to add CustomerId column in dbo.Orders table first. The column Name does not has to match with first table column in our case dbo.Customer.CustomerId
--Add new column to Table in case you don't have
Altertable dbo.Orders
Add CustomerId int
--Add Foreign Key Constraint on Existing Table
Altertable dbo.Orders
AddConstraint Fk_CustomerId
ForeignKey(CustomerId) References dbo.Customer(CustomerId)
Create Foreign Key Constraint on Composite Columns
The below script can be used to create Foreign Key Constraint for Composite Columns.
USE YourDatabaseName
GO
CREATETABLE dbo.Customer (
Customerid INTIdentity(1,1)
,FName VARCHAR(100) NotNull
,LName VARCHAR(100)
,SSN VARCHAR(10) NotNull,
Constraint Pk_FName_SSN PrimaryKey (FName,SSN)
)
CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
,FirstName VARCHAR(100),
SSN VARCHAR(10) NotNull
)
Columns already exists in both tables so we don't have to add columns to second table. We only need to create Foreign Key Constrain. Below script can be used to create Foreign Key Constraint for composite columns.
Altertable dbo.Orders
AddConstraint Fk_Order_Customer_FName_SSN
FOREIGNKEY (FirstName,SSN) REFERENCES dbo.Customer(FName,SSN)
You will write you syntax for your table
Alter table dbo.YourTableName
Add Constraint Constraint_Name
Foreign Key (Column1FromYourTableName,Column2FromYourTable) References dbo.YourFirstTable(Column1FromPrimaryKey,Column2FromPrimaryKey)