简体   繁体   English

带有CASE语句的SQL UPDATE产生不完整的结果

[英]SQL UPDATE with CASE Statement Yields Incomplete Results

The following code is intended to update particular fields only when there's a value that relates to that field. 以下代码仅在存在与该字段相关的值时才更新特定字段。

It returns an incomplete set of values. 它返回一组不完整的值。 Millions of rows are correct, but several thousand rows have values incorrectly set to NULL. 数百万行是正确的,但数千行的值错误地设置为NULL。

Is this is SQL limitation, or am I missing something? 这是SQL限制,还是我错过了什么?

UPDATE a
    SET ResultType1 = CASE WHEN b.[Type] = 'type1' THEN b.value END
       ,ResultType2 = CASE WHEN b.[Type] = 'type2' THEN b.value END
    FROM tableA AS a
    INNER JOIN tableB AS b ON a.ID = b.ID

update particular fields only when there's a value that relates to that field 仅当存在与该字段相关的值时才更新特定字段

makes me think that you actually want to do this: 让我觉得你真的想这样做:

UPDATE a
  SET ResultType1 = CASE WHEN b.[Type] = 'type1' 
                           THEN b.value 
                         ELSE ResultType1 
                    END
    , ResultType2 = CASE WHEN b.[Type] = 'type2' 
                           THEN b.value 
                         ELSE ResultType2 
                    END
FROM tableA AS a
    INNER JOIN tableB AS b ON a.ID = b.ID

So, ResultType1/2 will be set to their existing values if the b.Type conditions are not met, INSTEAD of being set to NULL. 因此,如果不满足b.Type条件,则将ResultType1 / 2设置为其现有值,INSTEAD设置为NULL。

I am assuming that when you say "incomplete set of values", you mean that some are being set to NULL. 我假设当你说“不完整的值集”时,你的意思是有些被设置为NULL。

What is causing this behaviour is the implied ELSE NULL in CASE expressions. 导致此行为的原因是CASE表达式中隐含的ELSE NULL


If you actually want to update ResultType1 and ResultType2 with nulls, but only for those rows that are of different 'type' , a slightly different query will do: 如果您确实希望使用空值更新ResultType1ResultType2 ,但仅针对那些具有不同'type'行,则稍有不同的查询将执行:

UPDATE a
  SET ResultType1 = CASE WHEN b.[Type] = 'type1' 
                           THEN b.value 
                         ELSE NULL                 --- this line can be removed
                    END
    , ResultType2 = CASE WHEN b.[Type] = 'type2' 
                           THEN b.value 
                         ELSE NULL                 --- this one, too
                    END
FROM tableA AS a
    INNER JOIN tableB AS b ON a.ID = b.ID
WHERE b.[Type] IN ('type1', 'type2')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM