加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLSERVER 外键约束 以及它的级联删除

发布时间:2020-12-12 15:21:28 所属栏目:MsSql教程 来源:网络整理
导读:sql server中建立外键约束有3中方式: 1.enterprise manager中,tables,design table,设置table的properties, ?? 可以建立constraint,reference key; 2.enterprise manager中,diagrams,new diagrams,建立两个表的关系。 3.直接用transact sql语句。 三个方

sql server中建立外键约束有3中方式:
1.enterprise manager中,tables,design table,设置table的properties,
?? 可以建立constraint,reference key;
2.enterprise manager中,diagrams,new diagrams,建立两个表的关系。
3.直接用transact sql语句。

三个方法都需要先建立数据表。
--?创建表author :
create table [dbo].[author] (
?[id] [bigint] not null,
?[authorname] [char] (10) null,
?[address] [char] (480)? null,
?[introduction] [ntext]? null
)

--?创建表mybbs:
reate table [dbo].[mybbs] (
?[id] [bigint] identity (1,1) not null,
?[authorid] [bigint] not null,
?[title] [char] (40)? null,
?[date_of_created] [datetime] null,
?[abstract] [char] (480)? null,
?[content] [ntext]? null
)

设置表mybbs中的authorid为外键,参照author表的id字段,直接使用transact sql语句,过程如下:
--增加表mybbs(authorid)的外键约束fk_mybbs_author,表mybbs中的authorid受表author中的主键id约束:
begin transaction
alter table dbo.mybbs add constraint fk_mybbs_author
? foreign key (authorid)
? references? dbo.author([id]) on update cascade on delete cascade

--删除外键约束fk_mybbs_author:
--alter table dbo.mybbs drop constraint fk_mybbs_author
--rollback
commit transaction

上面on update cascade,on delete cascade两个选项,指明以后author表的id字段有delete,update操作时,mybbs表中的id也会被级联删除或更新。如果没有选中,是不可以对author表中已被mybbs表关联的id进行update或者delete操作的。


文章整理:站长天空 网址:http://www.z6688.com/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读