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操作的。
本文介绍了在 SQL Server 中通过三种方法实现外键约束的过程,包括使用 Enterprise Manager 和 Transact-SQL 语句的方式,并详细展示了如何创建及删除外键约束。
550

被折叠的 条评论
为什么被折叠?



