惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
Martin Fowler
Martin Fowler
爱范儿
爱范儿
IT之家
IT之家
Last Week in AI
Last Week in AI
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
aimingoo的专栏
aimingoo的专栏
G
Google Developers Blog
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
The Cloudflare Blog
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
云风的 BLOG
云风的 BLOG
Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
腾讯CDC
Microsoft Security Blog
Microsoft Security Blog

博客园 - gamebaby

去掉rhel 6的缺少授权证书提示 c++消息 脚踏实地向前走 读xml内容 - gamebaby - 博客园 InvokeMember Invoke 项目经理应该知道的. Clear Sqlserver log 获取表信息 Email(VB.net) - gamebaby - 博客园 Email(C#) - gamebaby - 博客园 转义符 常规触发器 创建数据库 触发器 CASE 语句 事务处理 游标例子2(转载) 游标例子1(转载)
主外键
gamebaby · 2006-11-11 · via 博客园 - gamebaby

create table test1
(
 pub_id varchar(20) primary key,
 pub_name varchar(50),
 address varchar(20),
 city varchar(10),
 state char(2),
 country char(10)
)
go

create table test2
(
 author_id varchar(20) primary key,
 author_name varchar(50),
 phone varchar(20),
 zipcode char(10)
)
go

create table test3
(
 title_id int primary key,
 title_name varchar(50),
 author_id varchar(20) constraint fk_auid
           foreign key references test2(author_id)
           on delete cascade,
 pub_id varchar(20) foreign key references test1(pub_id),
)
go

insert into test1(pub_id,pub_name) values('pub001','pubaaa');
insert into test1(pub_id,pub_name) values('pub002','pubbbb');
insert into test1(pub_id,pub_name) values('pub003','pubccc');

insert into test2(author_id,author_name) values('au001','auaaa');
insert into test2(author_id,author_name) values('au002','aubbb');
insert into test2(author_id,author_name) values('au003','auccc');

insert into test3 values(1,'taaa','au001','pub001');
insert into test3 values(2,'taaa','au002','pub002');
insert into test3 values(3,'taaa','au003','pub003');
insert into test3 values(4,'taaa','au004','pub004'); --error,违反外键约束。

--删除pub_id = 'pub001' 的相关记录
delete from test1 where pub_id='pub001'; --no way
--应该这样做:先删外键表,再删主键表。
delete from test3 where pub_id='pub001';
delete from test1 where pub_id='pub001'; --ok

--删除au_id = 'au001' 的相关记录
delete from test2 where author_id = 'au002'; --ok,请注意test3表中的相关记录也同时被删除了。