Adding a FOREIGN KEY to the Employees Table : Foreign Key « Constraints « SQL Server / T-SQL Tutorial






6> CREATE TABLE Employees
7> (empid int NOT NULL primary key,
8>  mgrid int NULL,
9>  empname varchar(25) NOT NULL,
10>  salary money NOT NULL);
11> GO
1>
2> INSERT INTO employees(empid, mgrid, empname, salary) VALUES( 1, NULL, 'Nancy',  $10000.00)
3> INSERT INTO employees(empid, mgrid, empname, salary) VALUES( 2,    1, 'Andrew',  $5000.00)
4> INSERT INTO employees(empid, mgrid, empname, salary) VALUES( 3,    1, 'Janet',   $5000.00)
5> INSERT INTO employees(empid, mgrid, empname, salary) VALUES( 4,    1, 'Margaret',$5000.00)
6> INSERT INTO employees(empid, mgrid, empname, salary) VALUES( 5,    2, 'Steven',  $2500.00)
7> GO

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)

(1 rows affected)
1>
2>
3> ALTER TABLE Employees ADD CONSTRAINT FK_Employees_Employees
4>   FOREIGN KEY(mgrid)
5>   REFERENCES Employees(empid);
6> GO
1>
2> drop table Employees;
3> GO
1>
2>
3>








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