带Case的SQL Update,无论是分配还是什么都不做

时间:2012-03-21 21:03:20

标签: sql sql-server-2008 sql-update

在这个问题here的后面,有没有办法将CASE语句放入SQL UPDATE中,无论是更新还是什么都不做。目前我有以下内容:

UPDATE CustomerAddress
SET IsPrimaryAddress = CASE WHEN c2.IsPrimaryAddress=1 THEN 1 ELSE 0 END
FROM CustomerAddress
join #AddressToDeleteMasterOfLesserId p1 on CustomerAddress.Id=p1.[Id that is master]
join CustomerAddress c2 on p1.[Id to delete]=c2.Id 

问题出在这一行:

SET IsPrimaryAddress = CASE WHEN c2.IsPrimaryAddress=1 THEN 1 ELSE **0** END

当我将其设置为0时。更新应检查第一个条件,如果是,则设置为1,但是,如果条件不满足,我不想设置为0,我需要保留原始值。

SET IsPrimaryAddress = CASE WHEN c2.IsPrimaryAddress=1 THEN 1 ELSE *CustomerAddress.IsPrimary* END

但不起作用,因为它从FROM语句中获取值,而不是当前设置的值。我想要的是这样的东西

SET IsPrimaryAddress = CASE WHEN c2.IsPrimaryAddress=1 THEN 1 ELSE *Do nothing* END

但这仍然是一项任务,并尝试设置为NULL

以上可能吗?

更新:

示例数据:

代表地址的ID的对

ID to keep  ID to delete
------------------------
10          21
10          22
11          31
12          41

我会关注10所发生的事情。所以10有IsPrimaryAddress=0,21有IsPrimaryAddress=1,22有IsPrimaryAddress=0

我认为发生的是(伪代码):

设置IsPrimaryAddress =如果21.IsPrimaryAddress = 1则设置为21.IsPrimaryAddress,否则设置为10.IsPrimaryAddress

所以我们将10.IsPrimaryAddress设置为1.现在:

设置IsPrimaryAddress =如果22.IsPrimaryAddress = 1则设置为22.IsPrimaryAddress,否则设置为10.IsPrimaryAddress

我希望10.IsPrimaryAddress等于1.但它似乎得到原始值为0,现在更新已丢失。

3 个答案:

答案 0 :(得分:3)

只需添加一个WHERE子句,以便只更新需要更新的行:

UPDATE CustomerAddress c1
  INNER JOIN #AddressToDeleteMasterOfLesserId p1 ON c1.Id = p1.[Id that is master]
  INNER JOIN CustomerAddress c2 ON p1.[Id to delete] = c2.Id
  SET c1.IsPrimaryAddress = 1
  WHERE c2.IsPrimaryAddress = 1

答案 1 :(得分:2)

SET CustomerAddress.IsPrimaryAddress = 
      CASE 
         WHEN c2.IsPrimaryAddress=1 
         THEN 1 
         ELSE CustomerAddress.IsPrimaryAddress 
      END

PS:我不确定表名,但想法是返回列值本身以保持不变,这是一种常见做法。

答案 2 :(得分:1)

UPDATE c
SET IsPrimaryAddress = CASE 
  WHEN c2.IsPrimaryAddress = 1 THEN 1 
  ELSE c.IsPrimaryAddress
END
FROM dbo.CustomerAddress AS c
INNER JOIN #AddressToDeleteMasterOfLesserId AS p1 
  ON c.Id = p1.[Id that is master]
INNER JOIN dbo.CustomerAddress AS c2 
  ON p1.[Id to delete] = c2.Id;