在删除带有声明子变量的父行时如何删除子行

时间:2019-06-13 18:55:45

标签: sql sql-server stored-procedures

我目前正在处理一个SQL项目。我想创建一个存储过程来删除数据库中的行。唯一的问题是,当我删除一行时,有多个使用该变量的子行。我先给出一些背景。我有一个存储出租车的数据库。这是我用来删除的表格(我把一些列留得更清楚了)

create table User
(

    (primary key)UserID         int,
)

create table Rating
(


    (primary key)RatingID       int,
    (foreign key)UserID         int,
)

create table Complaint
(


    (primary key)ComplaintID        int,
    (foreign key)RatingID       int,
)

这是我用于删除用户的存储过程。如何删除行投诉(与“评分”>“用户”有关系)?我需要在某处声明ratingID吗?

create procedure SPDeleteUser
(
    @UserID int,
)
as
begin 
begin transaction

select UserID from Rating
delete from Complaint where UserID = @UserID

select UserID from Rating
delete from Rating where UserID = @UserID

select UserID from User
delete from User where UserID = @UserID

if @@ERROR <> 0
begin
rollback transaction
raiserror('Can't delete the user make sure the values are correct', 16, 
1)
return
end

commit
end
go

如何解决当我输入UserID时,行(关系用户>评分和评分>投诉)会自动删除的问题?

编辑! 使用ON DELETE CASCADE修复了该问题。现在,我只有下一条删除语句。

delete from Rating where UserID = @UserID
delete from User where UserID = @UserID

使用ON DELETE CASCADE约束,它会自动删除投诉行。谢谢您的帮助!仍然需要提高我的代码技能

1 个答案:

答案 0 :(得分:2)

您发布的代码到处都是。它与交易相关,可以回滚但不启动。那会导致错误。该错误几乎毫无价值,因为如果您在前两个删除操作中遇到任何一个错误,您将像这样错过它。

很确定您正在寻找符合这些原则的东西。

create procedure SPDeleteUser
(
    @UserID int
)
as
begin 

    set nocount on;

    begin transaction

    begin try

        --select UserID from Rating
        delete from Complaint where UserID = @UserID

        --select UserID from Rating
        delete from Rating where UserID = @UserID

        --select UserID from [User]
        delete from [User] where UserID = @UserID

        commit transaction
    end try

    begin catch
        rollback transaction
        raiserror('Can''t delete the user make sure the values are correct', 16, 1) 
        --just my 2¢ but this error is useless. It does not provide any details about what is actually wrong.
        --Instead you should get the actual error message and raise that so you know what the problem is. 
    end catch

end