为了防止添加重复的购物车,我试图修改我的存储过程以使用NOT EXISTS。我之前在WHERE语句中使用过这个,但这个是一个谜题。如果CartID已经存在,如何将NOT EXISTS应用于退出整个过程的Orders插入。
ALTER PROCEDURE [dbo].[CreateCustomerOrder]
(@CartID char(36),
@CustomerID uniqueidentifier,
@ShippingID int,
@TaxID int)
AS
/* Insert a new record into Orders */
DECLARE @OrderID int
INSERT INTO Orders (CustomerID, ShippingID, TaxID)
VALUES (@CustomerID, @ShippingID, @TaxID)
/* Save the new Order ID */
SET @OrderID = @@IDENTITY
/* Add the order details to OrderDetail */
INSERT INTO OrderDetail
(OrderID, ProductID, ProductName, Quantity, UnitCost)
SELECT
@OrderID, Product.ProductID, Product.Name,
ShoppingCart.Quantity, Product.Price
FROM Product JOIN ShoppingCart
ON Product.ProductID = ShoppingCart.ProductID
WHERE ShoppingCart.CartID = @CartID
/* Update Product Inventory */
UPDATE p
SET inventory = p.inventory - b.qty
FROM product as p,
(SELECT productid
,sum(quantity) as qty
FROM shoppingcart
WHERE cartid=@CartID
GROUP BY productid
) b
WHERE p.productid=b.productid
/* Clear the shopping cart */
DELETE FROM ShoppingCart
WHERE CartID = @CartID
/* Return the Order ID */
SELECT @OrderID
答案 0 :(得分:1)
将插入更改为:
INSERT INTO OrderDetail
(OrderID, ProductID, ProductName, Quantity, UnitCost)
SELECT @OrderID, Product.ProductID, Product.Name,
ShoppingCart.Quantity, Product.Price
FROM Product JOIN ShoppingCart
ON Product.ProductID = ShoppingCart.ProductID
WHERE NOT EXISTS (SELECT 1 FROM ShoppingCart a WHERE a.CartID = @CartID)