2016-11-09 25 views
2

美好的一天。我有3个表:插入数据如果不存在(来自2个表格)并更新

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是焦炭和产品ID 2是百事可乐)在另一方面
科X具有这个产品。股票:

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

我目前正在检查是否在tblBranchProducts存在从tblStockMoves的项目。

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

我之下,但到目前为止,使用此查询,它是所有更新的ProductID 1的股票,而忽略(不插入)产品ID 2.

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

您可以为所有产品出来IF的,只是需要addthe条件动态地做到这一点:

/*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 
+0

感谢鹭。但是,我注意到,如果tblBranchProducts上存在相同的产品ID,但是在不同的位置(如分支Z),查询将不会执行插入操作。是否有解决方法只为分支Y插入产品(并忽略分支Y上的相同项目?提前致谢! – Saudate

相关问题