更新列值,其中列值与另一个表不同

时间:2011-11-09 18:00:07

标签: sql-server sql-server-2008

我有两个具有相同模式的表,一个是数据被批量加载到的表,另一个是我的实时表。我想从上传的表中更新实时表,其中行是不同的。我想我离这里很近,但我的UPDATE会在哪里发挥作用?

这给了我更新的行,这些行实际上有我想要进入我的实时表的更改:

SELECT USC.* FROM UpdateStagingCustomers AS USC
JOIN StagingCustomers AS SC
ON USC.CustomerNumber = SC.CustomerNumber
AND USC.ManufacturerID = SC.ManufacturerID
WHERE USC.ManufacturerID=18 AND SC.ManufacturerID = 18
    AND USC.CustomerNumber IN(
        SELECT CustomerNumber FROM StagingCustomers WHERE ManufacturerID=18
    )
    AND 
    (
    USC.Address1 <> SC.Address1 OR
    USC.Address2 <> SC.Address2 OR
    USC.AuthorizedDealer <> SC.AuthorizedDealer OR
    USC.City <> SC.City
    )

1 个答案:

答案 0 :(得分:2)

我相信这个SQL语句可以完成这项工作,但您可能希望在回滚事务中对其进行测试。

UPDATE StagingCustomers 
SET Address1 = USC.Address1, 
    Address2 = USC.Address2, 
    AuthorizedDealer = USC.AuthorizedDealer,
    City = USC.City
FROM UpdateStagingCustomers AS USC
JOIN StagingCustomers AS SC
ON USC.CustomerNumber = SC.CustomerNumber
AND USC.ManufacturerID = SC.ManufacturerID
WHERE USC.ManufacturerID=18 AND SC.ManufacturerID = 18
    AND USC.CustomerNumber IN(
        SELECT CustomerNumber FROM StagingCustomers WHERE ManufacturerID=18
    )
    AND 
    (
    USC.Address1 <> SC.Address1 OR
    USC.Address2 <> SC.Address2 OR
    USC.AuthorizedDealer <> SC.AuthorizedDealer OR
    USC.City <> SC.City
    )