我可以在保持功能的同时组合多个更新语句吗

时间:2016-11-10 13:56:56

标签: sql sql-server tsql ssms

我正在浏览一个存储过程,当我遇到类似于下面的13个更新语句时,我试图对其进行优化。我想知道是否有人有比这更好的解决方案。我知道我可以使用case语句或合并,这在语义上是相同的,但请记住,所有列都将始终更新。这可能不会给您带来任何问题,但我可能会有很高的事务量,因此这种方法可能会导致并发问题。

UPDATE  COGS
SET     Revenue = 0
WHERE   Revenue IS NULL
        AND monthDate = @targetCOGSdate;

UPDATE  COGS
SET     Costs = 0
WHERE   Costs IS NULL
        AND monthDate = @targetCOGSdate;

UPDATE  COGS
SET     Disposal = 0
WHERE   Disposal IS NULL
        AND monthDate = @targetCOGSdate;

UPDATE  COGS
SET     Trans = 0
WHERE   Trans IS NULL
        AND monthDate = @targetCOGSdate;

2 个答案:

答案 0 :(得分:2)

是的,请使用COALESCE()

UPDATE COGS
    SET Revenue = COALESCE(Revenue, 0),
        Costs = COALESCE(Costs, 0),
        Disposal = COALESCE(Disposal, 0),
        Trans = COALESCE(Trans, 0)
    WHERE monthDate = @targetCOGSdate AND
          (Revenue IS NULL OR Costs IS NULL OR Disposal IS NULL OR Trans IS NULL);

答案 1 :(得分:1)

如果列为空,则使用coalesce表达式将列设置为0:

UPDATE  COGS
SET Revenue  = coalesce(Revenue, 0),
    Costs    = coalesce(Costs, 0),
    Disposal = coalesce(Disposal, 0),
    Trans    = coalesce(Trans, 0)
WHERE (Revenue IS NULL or Costs IS NULL or Disposal IS NULL or Trans IS NULL)
  AND monthDate = @targetCOGSdate;

但你为什么要这样做?我保留了NULL!