如果对 Customers 表的某行执行 UPDATE 语句,并且为 Orders.CustomerID 指定 ON UPDATE CASCADE 操作,则 SQL Server 将在 Orders 表中检查是否有与被更新行相关的一行或多行。如果存在相关行,那么 Orders 表中的相关行将随 Customers 表中的被引用行一同更新。
反之,如果指定了 NO ACTION,若在 Orders 表中至少存在一行引用 Customers 表中要更新的行,那么 SQL Server 将引发一个错误并回滚 Customers 表中的更新操作。 3,一个SQL创建外键的例子:
/*建库,名为student_info*/
create database student_info
/*使用student_info*/
use student_info
go
/*建student表,其中s_id为主键*/
create table student
(
s_id int identity(1,1) primary key,
s_name varchar(20) not null,
s_age int
)
go
/*建test表,其中test_no为主键*/
create table test
(
test_no int identity(1,1) primary key,
test_name varchar(30),
nax_marks int not null default(0),
min_marks int not null default(0)
)
go
/*建marks表,其中s_id和test_no为外建,分别映射student表中的s_id和test表中的test_no*/
create table marks
(
s_id int not null,
test_no int not null,
marks int not null default(0),
primary key(s_id,test_no),
foreign key(s_id) references student(s_id),
foreign key(test_no) references test(test_no)
)
go