• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

数据库主键,外键,关系,级联保存、更_sqlserver

sqlserver 搞代码 3年前 (2018-06-16) 95次浏览 已收录 0个评论

–建立数据库
create database test;
go

–建立表customers
create table customers(

http://www.gaodaima.com/36034.html数据库主键,外键,关系,级联保存、更_sqlserver

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;

欢迎大家阅读数据库主键,外键,关系,级联保存、更_sqlserver,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址