在DELETE中使用INNER JOIN

时间:2017-03-28 11:48:53

标签: sql sql-server

我正在尝试以下条件:如果Loans表中的任何贷款具有OutstandingAmount< 0,删除数据库中的所有相关信息。 我必须在一个命令中完成它,因此,我尝试使用INNER JOIN:

DELETE A, B, C, D, E
FROM Loans AS T1
INNER JOIN Payments T2 ON T1.LoanID = T2.LoanID
INNER JOIN Repayments T3 ON T1.LoanID = T3.LoanID
INNER JOIN Histories T4 ON T1.LoanID = T4.LoanID
INNER JOIN LoanRequests T5 ON T1.RequestDate = T5.RequestDate AND T1.BID = T5.BID
INNER JOIN Commits T6 ON T1.RequestDate = T6.requestDate AND T1.BID = T6.BID
WHERE T1.OutstandingAmount < 0

但是,这个命令在“DELETE A,B”中给出了语法错误,我甚至不确定这是否有效。 任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:4)

正如Gordon Linoff在评论中写道,你只能从每个删除声明中的一个表中删除。

你基本上有两个选择:

  1. 在外键中使用删除级联(这可能是最好的 事情要做)

  2. 对每个表使用delete语句,但将整个删除过程包装在事务中。

  3. 将删除级联添加到外键意味着删除并重新创建它们:

    ALTER TABLE dbo.Loans
    DROP CONSTRAINT FK_Loans_Payments; 
    
    ALTER TABLE dbo.Loans
    ADD CONSTRAINT FK_Loans_Payments FOREIGN KEY (LoanID) REFERENCES Payments(LoanID) ON DELETE CASCADE; 
    

    使用事务来包装单个删除语句:

    BEGIN TRASACTION
    
    BEGIN TRY
    
    DELETE c
    FROM Commits 
    INNER JOIN Loans l ON l.RequestDate = c.RequestDate 
    WHERE l.OutstandingAmount < 0
    
    DELETE lr
    FROM LoanRequests lr
    INNER JOIN Loans l ON l.RequestDate = lr.RequestDate 
    WHERE l.OutstandingAmount < 0
    
    -- more of the same...
    
    DELETE 
    FROM Loans
    WHERE OutstandingAmount < 0
    
    COMMIT TRANSACTION
    
    END TRY
    BEGIN CATCH
    
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION
    END CATCH