尝试这个:
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。