Is it possible to delete from multiple tables in the same SQL statement?

后端 未结 5 1492
自闭症患者
自闭症患者 2020-11-27 07:10

It\'s possible to delete using join statements to qualify the set to be deleted, such as the following:

DELETE J
FROM Users U
inner join LinkingTable J on U.         


        
5条回答
  •  清酒与你
    2020-11-27 07:41

    Nope, you'd need to run multiple statements.

    Because you need to delete from two tables, consider creating a temp table of the matching ids:

    SELECT U.Id INTO #RecordsToDelete
    FROM Users U
       JOIN LinkingTable J ON U.Id = J.U_Id
    ...
    

    And then delete from each of the tables:

    DELETE FROM Users 
    WHERE Id IN (SELECT Id FROM #RecordsToDelete)
    
    DELETE FROM LinkingTable
    WHERE Id IN (SELECT Id FROM #RecordsToDelete)
    

提交回复
热议问题