0

我从选择查询中得到一个值列表。从列表中,我正在检查列表中的项目是否在表中可用。如果值存在,我需要更新值否则将列表插入表中。

使用列表,我可以在表中插入值列表。如何在sql中检查和更新列表。

我的查询:

 WITH pq AS
    (
    SELECT A.[ProductId] ,A.[Quantity],A.[OrderId],D.[ProductName],E.[SpecialPrice],E.[SpecialPrice]*A.[Quantity] AS SPrice FROM [Table1]  A
    LEFT JOIN [Table2]  B ON A.[OrderId] = B.[OrderId] INNER JOIN [Table3]  D
    ON A.[ProductId] = D.[ProductId] INNER JOIN [Table4] E
    ON A.[ProductId] = E.[ProductId] WHERE B.[CustomerId] = 1       
    AND A.[OrderId] = 77 
    )
    IF (EXISTS(SELECT [ProductId] FROM [Table5] WHERE [ProductId] = A.[ProductId]))
    BEGIN
    UPDATE [Table5]
    SET [Quantity] = A.[Quantity]
    WHERE B.[CustomerId] = 1 AND [ProductId] = A.[ProductId]
    END
    ELSE
    BEGIN
    INSERT INTO [Table5]
    ([ProductId],[ProductName],[Quantity],[Price],[TotalAmount])
    SELECT
    [ProductId],[ProductName],[Quantity],[SpecialPrice],SPrice
    FROM pq;
    END

任何建议都会很有帮助。

编辑:选择查询结果

ProductId Quantity

   65       2

   64       1
4

1 回答 1

2

假设您使用的是 SQL Server 2008 或更高版本,MERGE语句将解决您的问题:

MERGE Table5 TRG
USING (
    SELECT
        A.ProductId,
        A.Quantity,
        A.OrderId,
        D.ProductName,
        E.SpecialPrice,
        (E.SpecialPrice * A.Quantity) SPrice
    FROM Table1 A
        LEFT JOIN Table2 B ON A.OrderId = B.OrderId
        INNER JOIN Table3 D ON A.ProductId = D.ProductId
        INNER JOIN Table4 E ON A.ProductId = E.ProductId
    WHERE
        B.CustomerId = 1       
        AND A.OrderId = 77 
) SRC
ON TRG.ProductID = SRC.ProductID
WHEN MATCHED THEN
    UPDATE SET TRG.Quantity = SRC.Quantity
WHEN NOT MATCHED BY TARGET THEN
    INSERT (
        ProductId
        , ProductName
        , Quantity
        , Price
        , TotalAmount
    )
    VALUES (
        SRC.ProductId
        , SRC.ProductName
        , SRC.Quantity
        , SRC.SpecialPrice
        , SRC.SPrice)
;

您可以像在示例中那样将 SELECT 查询移到CTE以提高可读性。

于 2013-08-29T10:39:47.450 回答