使用选择查询删除记录

时间:2014-04-26 09:20:33

标签: sql-server sql-server-2008 tsql

我想删除以下查询返回的所有记录:

    SELECT *
    FROM [Customer] C
    INNER JOIN [BillingStatus] BS 
    ON BS.CustomerID = C.CustomerID 
    INNER JOIN [TCDetails] TC 
    ON TC.CustomerID = BS.CustomerID    
    INNER JOIN [BillingDetails] BD 
    ON BS.CustomerID = BD.CustomerID
    INNER JOIN [AgencyDetails] AD
    ON BD.CustomerID = AD.CustomerID
    INNER JOIN [CustomerDetails] CD
    ON CD.CustomerID = AD.CustomerID
    WHERE C.CYC = 27    

2 个答案:

答案 0 :(得分:2)

您想要从所有表中删除,因此首先将客户ID声明为某个临时表可能会更简单:

SELECT CustomerID 
INTO #TempCustomer 
FROM Customer
WHERE CYC = 27

然后,您需要从每个表中删除:

DELETE FROM Customer WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)
DELETE FROM BillingStatus WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)
DELETE FROM TCDetails WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)
DELETE FROM BillingDetails WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)
DELETE FROM AgencyDetails WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)
DELETE FROM CustomerDetails WHERE CustomerID IN (SELECT CustomerID FROM #TempCustomer)

最后,为了清理你,你应该删除你创建的临时表:

DROP TABLE #TempCustomer

答案 1 :(得分:0)

从您的评论中删除Customer及其他表中的所有关系,首先将Cascade Delete的外键设置为Customer到其他表,然后Delete具有此查询的客户将删除所有其他表

DELETE FROM [Customer] WHERE CYC = 27