您的位置:首页 > 数据库

sql server中的外键约束

2004-10-16 16:24 453 查看
Author:David Euler
Date: 2004/10/16
Email:de_euler-david@yahoo.com.cn

有任何问题,请与我联系:)

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
)



author-myBBS关系图

设置表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操作的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: