我有一个表:StudentHome,它对学生表有一个 fk 约束。因此,当学生被删除时,我还需要从 StudentHome 中删除记录。当我使用普通的删除语句时,我写了
Insert into Student
select studentId, (other fields) from #Student
Delete sh
from StudenHome sh
left join #Student temps on temps.StudentId = sh.fkStudentId
where temps.studentId is null
Delete s
from Student s
left join #Student temps on temps.StudentId = s.studentId
where temps.studentId is null
但是,当我尝试使用合并语句时,我不确定如何在从学生表中删除记录之前从学生之家删除记录。
merge into Student s
using #Student temps
on s.StudentID = temps.StudentId
when not matched by target then
insert ...
when not matched by source then
-- Delete from StudentHome
delete;
有没有办法实现上面的 sudo 代码,在从学生表中删除之前先从表中删除:StudentHome?
我不认为可以在单个语句中显式删除两个表。但是,您可以简单地使用两个合并语句来获得与两个删除语句等效的内容。 (或者如果更容易的话,甚至可以对第一部分使用删除语句。)
merge into StudentHome sh
using #Student temps
on sh.fkStudentId = temps.StudentId
when not matched by source then
delete;
merge into Student s
using #Student temps
on s.StudentID = temps.StudentId
when not matched by target then
insert ...
when not matched by source then
delete;