简体   繁体   中英

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.

Is this is SQL limitation, or am I missing something?

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.

I am assuming that when you say "incomplete set of values", you mean that some are being set to NULL.

What is causing this behaviour is the implied ELSE NULL in CASE expressions.


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:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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