When working with constraints in SQL Server, you can use the following syntax to add a foreign key constraint:
- ADD CONSTRAINT:
ALTER TABLE [TableName]
ADD CONSTRAINT [ConstraintName]
FOREIGN KEY ([ColumnName])
REFERENCES [ReferencedTableName]([ReferencedColumnName]);
This syntax adds a new constraint to the table, specifying the type of constraint (in this case, a foreign key constraint) and its properties.
- CHECK CONSTRAINT:
ALTER TABLE [TableName]
ADD CONSTRAINT [ConstraintName]
CHECK ([Condition]);
This syntax adds a check constraint to the table, which ensures that the data in the table meets a specific condition. However, this syntax is not used to create a foreign key constraint.
- CHECK ADD CONSTRAINT:
This syntax is not a valid SQL Server syntax. You can either use
ADD CONSTRAINT to add a constraint, or CHECK to specify a condition for a check constraint.
To create a foreign key constraint, you should use the ADD CONSTRAINT syntax, as shown in the first example.
However, you can use a combination of ADD CONSTRAINT and CHECK to create a foreign key constraint with additional check conditions. For example:
ALTER TABLE [TableName]
ADD CONSTRAINT [ConstraintName]
CHECK ([Condition])
FOREIGN KEY ([ColumnName])
REFERENCES [ReferencedTableName]([ReferencedColumnName]);
This syntax creates a foreign key constraint that also checks an additional condition. However, this is not a common use case, and it's generally recommended to keep foreign key constraints and check constraints separate.
In summary:
ADD CONSTRAINT is used to add a new constraint to a table, including foreign key constraints.
CHECK CONSTRAINT is used to add a check constraint to a table, which ensures that the data meets a specific condition.
CHECK ADD CONSTRAINT is not a valid syntax.
- You can use
ADD CONSTRAINT with a foreign key constraint to create a foreign key constraint, and optionally add additional check conditions using the CHECK keyword.
Here's an example that demonstrates the difference:
-- Create a table with a foreign key constraint
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
);
-- Create a table with a check constraint
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
CONSTRAINT CK_Orders_CustomerID
CHECK (CustomerID > 0)
);
-- Create a table with both a foreign key constraint and a check constraint
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID),
CONSTRAINT CK_Orders_CustomerID
CHECK (CustomerID > 0)
);