34,590
社区成员
发帖
与我相关
我的任务
分享
create table T(ID int unique)
create table T2(t_id int references t(ID) on delete cascade on update cascade)
insert T select 1
insert T2 select 1
insert T2 select 1
-------
update T set ID=2
select * from T2
---
delete T
select * from T2
约束:
以外键约束为例说明一下:
1、创建测试环境:
if exists (select 1
from sysobjects
where id = object_id('dbo.tab1')
and type = 'U')
drop table dbo.tab1
go
/*==============================================================*/
/* Table: tab1 */
/*==============================================================*/
create table dbo.tab1 (
personid char(2) not null,
personname varchar(10) null,
depid char(4) null,
constraint PK_TAB1 primary key (personid)
)
go
alter table dbo.tab1
add constraint FK_TAB1_REFERENCE_TAB2 foreign key (depid)
references dbo.tab2 (depid)
go
alter table dbo.tab1
drop constraint FK_TAB1_REFERENCE_TAB2
go
if exists (select 1
from sysobjects
where id = object_id('dbo.tab2')
and type = 'U')
drop table dbo.tab2
go
/*==============================================================*/
/* Table: tab2 */
/*==============================================================*/
create table dbo.tab2 (
depid char(4) not null,
depname varchar(10) null,
constraint PK_TAB2 primary key (depid)
)
go
alter table dbo.tab1
add constraint FK_TAB1_REFERENCE_TAB2 foreign key (depid)
references dbo.tab2 (depid)
go
2、插入测试数据:
insert tab2
select '0001','综合办公室' union all
select '0002','采购部'
insert tab1
select '01','张三','0001' union all
select '02','李四','0002' union all
select '03','王五','0001' union all
select '04','薛六','0002'
3、以添加数据、删除数据、删除表三个例子说明一下约束的作用:
(1)、添加数据时,如果在部门表里面没有的部门编号,在人员信息表不允许录入,测试如下:
insert tab1
select '05','张三','0003'
错误提示:
消息 547,级别 16,状态 0,第 1 行
INSERT 语句与 FOREIGN KEY 约束"FK_TAB1_REFERENCE_TAB2"冲突。该冲突发生于数据库"DB_ACSERP",表"dbo.tab2", column 'depid'。
语句已终止。
(2)在删除部门表中的数据时,如果要删除的数据存在于人员信息表中,不允许删除:
delete from tab2 where depid='0001'
错误提示:
消息 547,级别 16,状态 0,第 1 行
DELETE 语句与 REFERENCE 约束"FK_TAB1_REFERENCE_TAB2"冲突。该冲突发生于数据库"DB_ACSERP",表"dbo.tab1", column 'depid'。
语句已终止。
(3)删除表:
drop table tab2
错误提示:
消息 3726,级别 16,状态 1,第 1 行
无法删除对象 'tab2',因为该对象正由一个 FOREIGN KEY 约束引用。
4、删除测试环境:
drop table tab1
drop table tab2
完成。
通过以上内容,你应该可以理解了外键约束的使用方法了。
ALTER 表1 ADD Constraint FK_表1_表2 FOREIGN KEY(表1.外键字段) REFERENCES 表2(表2.主键字段)
ALTER 表1 ADD Constraint FK_表1_表2 FOREIGN KEY(表1.外键字段) REFERENCE 表2(表2.主键字段)