如果不存在则插入数据(来自2个表),否则更新

时间:2016-11-09 14:34:55

标签: sql sql-server insert-update

美好的一天。我有3张桌子:

tblWarehouseProducts

 ProductID
 ProductName
 ProductCode
 Quantity

tblBranchProducts

 ProductID
 ProductCode
 ProductCode
 Quantity
 Location

tblStockMoves

 ProductID
 DestinationLocation
 Quantity
 ReferenceNumber

基本上,流程是分支X从仓库Y请求产品。仓库Y然后创建请求订单(称为库存移动)并将请求存储在 tblStockMove

对于这种情况,我们有一个参考编号为XYZ的股票移动:

REFERENCE NO.  |   PRODUCT ID  |   DESTINATION   |   QTY   |
XYZ            |       1       |     BRANCH Y    |    5    |
XYZ            |       2       |     BRANCH Y    |    6    |

(其中ProductID 1为Coke,ProductID 2为百事可乐。)另一方面,Branch X有此产品有货:

PRODUCT ID  |  PRODUCT NAME   | PRODUCT CODE  |   QUANTITY |   LOCATION   |
1           |      COKE       |    ABC123     |      6     |    Branch X  |

我目前正在尝试检查来自tblStockMoves的项目是否存在于tblBranchProducts中。

如果产品1存在,它会将tblStockMoves中的Qty添加到tblBranchProducts中的当前数量。产品2将作为新条目添加,因为它是一个新项目。

我在下面使用此查询,但到目前为止,它只是在忽略(不插入)产品ID 2时更新ProductID 1的库存。

IF EXISTS (select ProductID, Location 
           from tblBranchProducts a 
           where Location = 'Branch X' 
             and a.ProductID in (select b.ProductID  
                                 from tblStockMoves b 
                                 where b.ReferenceNumber = 'XYZ' 
                                   and b.DestinationLocation = 'Branch X'))
BEGIN
    UPDATE tblBranchProducts 
    SET Quantity = a.Quantity + b.Quantity
    FROM tblBranchProducts a 
    INNER JOIN tblStockMoves b ON a.ProductID = b.ProductID 
    WHERE 
        b.ReferenceNumber = 'XYZ' 
        AND b.DestinationLocation = 'Branch X'
END
ELSE
BEGIN
    INSERT INTO tblBranchProducts (ProductID, ProductName, ProductCode, Quantity, Location) 
        SELECT 
            b.ProductID, a.ProductName, a.ProductCode, b.Quantity, b.DestinationLocation 
        FROM 
            tblStockMoves b 
        INNER JOIN
            tblWarehouseProducts a ON b.ProductID = a.ProductID 
        WHERE 
            b.ReferenceNumber = 'XYZ' 
            AND b.DestinationLocation = 'Branch X'

产品名称和产品代码等其他详细信息从tblWarehouseProducts中提取,然后插入到tblBranchProducts中。

有谁可以告诉我为什么我的查询只更新产品1的现有库存而不插入产品2?

非常感谢您的回答!

1 个答案:

答案 0 :(得分:1)

您可以动态执行IF以外的所有产品,只需添加所需条件:

/*will insert all the unmatched products*/
INSERT INTO tblBranchProducts  (ProductID, ProductName, ProductCode, Quantity, Location) 
SELECT b.ProductID, a.ProductName, a.ProductCode, b.Quantity, b.DestinationLocation
FROM tblStockMoves b
inner join tblWarehouseProducts a on b.ProductID = a.ProductID
LEFT JOIN tblBranchProducts  c ON(a.productid = b.productid)
where  c.productid is null

/*will update all the matching products*/
update tblBranchProducts a
INNER join tblStockMoves b on a.productid = b.productid
set a.quantity= b.qty