1

这是我的 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

我需要删除表中产品数量较大的行shoppingCartShoppingCart.QuantityProducts没有任何反应。

4

1 回答 1

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   

结果如下:

在此处输入图像描述

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

于 2012-12-01T01:13:52.693 回答