2012-12-01 121 views
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 

我需要從shoppingCart刪除該行地方ShoppingCart.Quantity較大產品的數量在Products表,但什麼都沒發生。

回答

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

注意的ProductID = 1的SellerID刪除1,因爲它在購物車中有10個,而產品表中的限制爲8個。但SellerId 2的超額限制仍然存在,因爲該過程一次只能用於一個SellerId。

+0

finaly它在這種方式工作,但任何方式非常感謝答案.. –

相關問題