数据库主键,外键,关系,级联保存、更新、删除
2024-07-21 02:11:51
供稿:网友
--建立数据库
create database test;
go
--建立表customers
create table customers(
id int identity(1,1) not null,
name varchar(15),
age int,
primary key(id)
);
go
--建立表orders
create table orders(
id int identity(1,1) not null,
order_number varchar(15),
price money,
customer_id int,
primary key(id)
);
go
--对表orders插入数据,以检测money数据类型,结果为:69.0000
insert into orders(price) values(69);
select * from orders;
--增加外键与关系约束
alter table orders add constraint fk_customer foreign key (customer_id) references customers(id);
go
--级联删除、更新
alter table orders add constraint fk_customer foreign key (customer_id) references customers(id)
on delete cascade on update cascade;
go
--级联删除
alter table orders add constraint fk_customer foreign key (customer_id) references customers(id)
on delete cascade;
go
=====================================================================================================
--
insert into customers values('张三',25);
insert into customers values('李四',25);
--如果设置了级联插入,那么在向子表orders插入的customer_id(外键)
--必须在父表customers中存在此id(主键)
insert into orders values(1,50,5);
--如果设置了级联删除,删除父表customers中id=5的记录,
--也会删除子表orders中customer_id=5的记录,
delete from customers where id=5
--查询
select * from customers;
select * from orders;