首页 > 数据库技术 > 详细

SQL Server外键约束

时间:2014-07-22 22:55:44      阅读:435      评论:0      收藏:0      [点我收藏+]

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的了

 

SQL Server外键约束,布布扣,bubuko.com

SQL Server外键约束

原文:http://www.cnblogs.com/cnmarkao/p/3848760.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!