从一个表中删除具有来自另一个表的条件的行

时间:2012-12-01 01:03:20

标签: sql-server

这是我的MS SQL代码:

ALTER PROCEDURE dbo.RemoveFromCart
  @SellerID int
AS
DELETE FROM ShoppingCart
  WHERE Quantity > (SELECT Products.Quantity FROM Products, ShoppingCart
    WHERE ShoppingCart.ProductID = Products.ProductID )
  AND ShoppingCart.SellerID = @SellerID

我需要删除shoppingCart中的行,其中ShoppingCart.Quantity大于Products表中产品的数量,但没有任何反应。

1 个答案:

答案 0 :(得分:2)

试试这个:

ALTER PROCEDURE dbo.RemoveFromCart
    @SellerID int
AS

    DELETE 
        cart

    FROM 
        ShoppingCart cart
    INNER JOIN Products prod
        ON cart.ProductID = prod.ProductID

    WHERE 
            cart.Quantity > prod.Quantity
        AND cart.SellerID = @SellerID;

你可以这样测试:

SELECT 
    ProductID, Quantity, SellerID
INTO ShoppingCart
FROM
(
    SELECT 1 AS ProductID, 10 AS Quantity, 1 AS SellerId UNION ALL
    SELECT 2 AS ProductID,  6 AS Quantity, 1 AS SellerId UNION ALL
    SELECT 3 AS ProductID,  8 AS Quantity, 2 AS SellerId UNION ALL
    SELECT 4 AS ProductID,  6 AS Quantity, 2 AS SellerId 
) X;

SELECT 
    ProductID, Quantity, SellerID
INTO Products
FROM
(
    SELECT 1 AS ProductID,  9 AS Quantity, 1 AS SellerId UNION ALL
    SELECT 2 AS ProductID,  8 AS Quantity, 1 AS SellerId UNION ALL
    SELECT 3 AS ProductID,  7 AS Quantity, 2 AS SellerId UNION ALL
    SELECT 4 AS ProductID,  6 AS Quantity, 2 AS SellerId 
) X;



Begin tran

select * from ShoppingCart;
select * from Products;

execute dbo.RemoveFromCart 1

select * from ShoppingCart;
select * from Products;
rollback tran   

结果如下:

enter image description here

请注意,对于SellerID 1,ProductID = 1已被删除,因为它在购物车中有10个,而在产品表中限制为8。但是对于SellerId 2的限制仍然存在,因为proc一次仅适用于一个SellerId。