[英]Constraint between tables in SQL Server, deleting one should delete the other
I am creating two tables RegistrationHeader and RegistrationDetail. 我正在创建两个表RegistrationHeader和RegistrationDetail。 How can i add a constraint that when i delete RegistrationHeader table to automaicaly delete the RegistrationDetail table.
我如何添加一个约束,以便在删除RegistrationHeader表时自动删除RegistrationDetail表。
create table RegistrationHeader(
RegistrationNo numeric
,BillingID varchar(30) not null
,RegistrationDate date not null
,PaymentType varchar check (PaymentType = 'CC' or PaymentType = 'PO' or PaymentType = 'Check') not null
,CCNumber numeric check(CCNumber >= 15 and CCNumber <=16)
,PONumber varchar(30)
,CheckNumber varchar(10)
,primary key(RegistrationNo)
,foreign key(BillingId) references Person(UserID)
,constraint CC_CCNumber_constr check(
(PaymentType = 'CC' and CCNumber is not null)
or
(PaymentType != 'CC' and CCNumber is null)
)
,constraint PO_PONumber_constr check(
(PaymentType = 'PO' and (PONumber is not null or PONumber != ''))
or
(PaymentType != 'PO' and PONumber is null)
)
,constraint CheckNumber_type_constr check(PaymentType != 'Check' and CheckNumber is null)
);
create table RegistrationDetail(
RegistrationNo numeric
,LineNumber numeric
,CourseID numeric(10) not null
,AttendeeID varchar(30) not null
primary key(RegistrationNo,LineNumber)
);
Thanks for the help! 谢谢您的帮助!
You will need to 您将需要
1) Set up foreign key relations between RegistrationHeader.RegistrationNo
and RegistrationDetail.RegistrationNo
1)在
RegistrationHeader.RegistrationNo
和RegistrationDetail.RegistrationNo
之间建立外键关系
2) Add ON DELETE CASCADE
to RegistrationDetail Foreign Key definition 2)将
ON DELETE CASCADE
添加到RegistrationDetail外键定义
I haven't tested this, but I believe this should be what you're looking for in SQL Server 我没有测试过,但是我相信这应该是您在SQL Server中寻找的东西
ALTER TABLE RegistrationDetail
ADD CONSTRAINT FK_RegistrationHeader_RegistrationDetail_Cascade
FOREIGN KEY (RegistrationNo) REFERENCES RegistrationDetail (RegistrationNo) ON DELETE CASCADE
Constrains are affecting only database columns such as primary/foreign keys or regular columns, not whole tables. 约束仅影响数据库列(例如主/外键或常规列),而不影响整个表。 You can add
OnDelete
or OnUpdate
constraints for foreign keys to delete/keep the refrences from one table to other but not the whole table. 您可以为外键添加
OnDelete
或OnUpdate
约束,以删除/保留从一个表到另一个表(而不是整个表)的引用。 That is mixing DML
(select,update,insert,delete) with DDL
(create,drop). 那就是将
DML
(选择,更新,插入,删除)与DDL
(创建,删除)混合在一起。 Try to read more about DML
and DDL
. 尝试阅读有关
DML
和DDL
更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.