如果ID在列中,如何从表中删除数据

时间:2014-12-12 15:18:38

标签: sql sql-server remove-if

我必须编写一个脚本,该脚本将提取所有成员的ID,这些成员的电子邮件已被硬退回。为了做到这一点,我写了这个

 Select id FROM Members m
 Join tbl_memberlanguageid mli on m.ID = mli.MLI_MemberID 
 Where Cast(dateCreated as date) >= '01-Dec-2014'
 and mli.MLI_LanguageID = 3 
 and EmailHardBounces = 1

然后我需要使用这个ID列表将它们从表Members中删除。我如何编写此脚本,以便在ID位于该列表中时从会员中删除与ID相关的所有内容?

3 个答案:

答案 0 :(得分:2)

您只需将Select id更改为Delete m

即可
BEGIN TRAN

DELETE  m
FROM    Members m
        JOIN tbl_memberlanguageid mli ON m.ID = mli.MLI_MemberID
WHERE   CAST(dateCreated AS DATE) >= '01-Dec-2014'
        AND mli.MLI_LanguageID = 3
        AND EmailHardBounces = 1

ROLLBACK
COMMIT

在提交删除之前,只需确认记录计数是否正确。

答案 1 :(得分:2)

我喜欢CTE,因为他们可以看到我要删除的内容:

WITH MemberIdsToDelete AS
(
     Select id FROM Members m
     Join tbl_memberlanguageid mli on m.ID = mli.MLI_MemberID 
     Where Cast(dateCreated as date) >= '01-Dec-2014'
     and mli.MLI_LanguageID = 3 
     and EmailHardBounces = 1
)
SELECT id FROM MemberIdsToDelete

如果您最终要删除它们,请替换

SELECT id FROM MemberIdsToDelete

DELETE FROM Members WHERE id IN (SELECT id FROM MemberIdsToDelete)

答案 2 :(得分:1)

另一种方式:

DELETE FROM Members WHERE ID IN(Select id FROM Members m
Join tbl_memberlanguageid mli on m.ID = mli.MLI_MemberID 
Where Cast(dateCreated as date) >= '01-Dec-2014'
and mli.MLI_LanguageID = 3 
and EmailHardBounces = 1)