SQL Server外键约束

SQL Server中主外键的定义:

1.

create table dept
(
dept_no int primary key,
dept_name nvarchar(50) not null
)
insert into dept values(10,'IT'),(20,'Finance'),(30,'Engneer')
create table employee ( employee_id int primary key, employee_name nvarchar(50) not null, dept_no int foreign key references dept(dept_no) )
上面的写法,是列级定义,直接定义列字段的时候定义foreign key

2.

create table dept
(
dept_no int primary key,
dept_name nvarchar(50) not null
prmary key (dept_no)
)
insert into dept values(10,'IT'),(20,'Finance'),(30,'Engneer')
create table employee
(
employee_id int primary key,
employee_name nvarchar(50) not null,
dept_no int,
constraint dept_no_fk foreign key(dept_no) references dept(dept_no)
)
这是表级的定义

3.已经创建了没有定义主外键的表,可以使用alter table修改

alter table employee 
add foreign key (dept_no) references dept(dept_no)


alter table employee
add constraint dept_no_fk foreign key (dept_no)
references dept(dept_no)

添加主键

alter table dept
add constraint dept_no_pk primary key(dept_no)

4.去除主键

alter table dept drop constraint dept_no_pk 

去除外键

alter table employee 
drop constraint dept_no_fk
 

建了删,删了建的,手疼原本打算把MySQL的语句也写上的,原因是昨晚看了关于MySQL的视频,关于check不起作用,而且自己外键约束也模糊,不知道怎么写,原来是两种写法,这也是看MySQL视频看到的。只好改天再写MySQL的了

 
原文地址:https://www.cnblogs.com/cnmarkao/p/3848760.html