1

假设我有两张桌子。 ErrorsErrorsDetails。所以我有一个错误记录,其中可能包含许多 ErrorDetails 记录。

用户将通过他们使用的应用程序定期删除详细记录。当所有详细记录都被清理(删除)后,我也想自动删除主记录。

一个很酷的 SQL 删除语句将删除详细信息和如果 master 没有更多详细信息,则删除 master。但我似乎无法得到一个干净的 SQL 语句来做到这一点。每次删除后,我宁愿不要轮询主人以获取详细信息。

错误

ID        Error
1         Import Error
2         Export Error

错误详情

ID        ErrorsID        DetailedInfo
1         1               Couldn't import file because of FTP error
2         1               Couldn't import file because of permission error
3         2               Couldn't export file because of directory doesn't exist

我试过cascade像这样添加一个删除约束,但它似乎没有用。

alter table dbo.ErrorsDetails
    add constraint FK_Delete_Master
        foreign key (ErrorsID) references dbo.Errors(ErrorsID) on delete cascade

感谢您的任何建议。

更新

有人提到使用触发器。我想过,但没有提及。触发器肯定会完成这项工作。这种情况下触发器的优点/缺点?

4

1 回答 1

2

您可以使用触发器或

declare @ErrorsId int
select @ErrorsId = ErrorsId from ErrorsDetails where ID = @id
delete from ErrorsDetails where ID = @id

declare @errorDetailCount int
select @errorDetailCount = count(*) from ErrorsDetails where ErrorsId = @ErrorsId 

if (@errorDetailCount = 0)
begin
 delete from Errors where ID = @ErrorsId 
end

更新:触发:

create trigger [dbo].[ErrorsDetails_Delete_Trigger] on [dbo].[ErrorsDetails] 
instead of delete
as 
begin          
    declare @ErrorsId int
    select @ErrorsId = ErrorsId from deleted
    delete from ErrorsDetails where ID = deleted.ID

    declare @errorDetailCount int
    select @errorDetailCount = count(*) from ErrorsDetails where ErrorsId = @ErrorsId 

    if (@errorDetailCount = 0)
    begin
     delete from Errors where ID = @ErrorsId 
    end     
end
于 2012-10-31T12:45:10.040 回答