DELETE具有另一个表的条件的表的行

时间:2013-11-27 05:43:31

标签: sql sql-server sql-server-2008-r2

我有以下SQL正在运行,

IF NOT EXISTS(SELECT 1 FROM [Batch] B 
INNER JOIN BatchProducts BP 
ON (B.ID = BP.BatchID) 
WHERE Bp.ID = @ID AND B.RetailerID = @RetailerID)
BEGIN
    RETURN; 
END
DELETE FROM BatchProducts WHERE  BatchProducts.ID = @ID;

但它由2个陈述组成。我想使用单个DELETE,条件是RetailerID必须在BatchProducts表中匹配。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

DELETE FROM BatchProducts
WHERE BatchProducts.ID = @ID
AND EXISTS (SELECT * FROM [Batch] 
    WHERE [Batch].ID = BatchProducts.BatchID AND [Batch].RetailerID = @RetailerID)

答案 1 :(得分:1)

是否有特殊原因需要检查它是否存在?

DELETE bp
FROM BatchProducts bp
    JOIN Batch b
        ON bp.BatchID = b.ID
WHERE bp.ID = @ID
AND b.RetailerID = @RetailerID