FOREIGN KEY Constraints : Foreign Key « Constraints « SQL Server / T-SQL Tutorial






<column name> <data type> <nullability>
FOREIGN KEY REFERENCES <table name>(<column name>)
    [ON DELETE {CASCADE|NO ACTION}]
    [ON UPDATE {CASCADE|NO ACTION}]

11> CREATE TABLE Customers (
12>     CustomerID nchar (5) NOT NULL PRIMARY KEY ,
13>     CompanyName nvarchar (40) NOT NULL ,
14>     ContactName nvarchar (30) NULL ,
15>     ContactTitle nvarchar (30) NULL ,
16>     Address nvarchar (60) NULL ,
17>     City nvarchar (15) NULL ,
18>     Region nvarchar (15) NULL ,
19>     PostalCode nvarchar (10) NULL ,
20>     Country nvarchar (15) NULL ,
21>     Phone nvarchar (24) NULL ,
22>     Fax nvarchar (24) NULL
23> )
24> GO
1>
2>
3>
4>    CREATE TABLE Orders
5>    (
6>       OrderID      int   IDENTITY   NOT NULL
7>          PRIMARY KEY,
8>       CustomerNo   nchar              NOT NULL
9>          FOREIGN KEY REFERENCES Customers(CustomerID),
10>       OrderDate    smalldatetime    NOT NULL,
11>       EmployeeID   int              NOT NULL
12>    )
13>    GO
Msg 1753, Level 16, State 1, Server J\SQLEXPRESS, Line 4
Column 'Customers.CustomerID' is not the same length as referencing column 'Orders.CustomerNo' in foreign key 'FK__Orders__Customer__43C1CFF5'. Columns participating in a foreign key relationship must
 be defined with the same length.
Msg 1750, Level 16, State 1, Server J\SQLEXPRESS, Line 4
Could not create constraint. See previous errors.








7.3.Foreign Key
7.3.1.The FOREIGN KEY Clause
7.3.2.FOREIGN KEY Constraints
7.3.3.A statement that adds a foreign key constraint
7.3.4.ON DELETE and ON UPDATE Options
7.3.5.Adding a FOREIGN KEY to the Employees Table
7.3.6.Re-creating the FOREIGN KEY with NO ACTION (Implicitly)
7.3.7.Referential Constraints
7.3.8.Cascading Updates and Deletes
7.3.9.Supporting Basic Referential Integrity with Foreign Keys