views:

62

answers:

2

This is basically an extension of Update multiple rows with one query?. I want to be able to update multiple columns of multiple rows at a time, but not necessarily to update every column of every row.

Here is an example command I would like to be able to execute:

UPDATE person
SET name = CASE id
    WHEN 1 THEN 'Jim'
    WHEN 3 THEN 'Precious'
END,
sex = CASE id
    WHEN 1 THEN 'female'
    WHEN 2 THEN 'male'
END
WHERE id IN (1,2,3)

However this returns an error, telling me column 'name' cannot be null. So it seem to me that specifying WHERE id IN (x,y,z) means all selected columns must be updated, even though we're indicating which values to place on a case by case basis.

Is there any way around this limitation, like a special notation to indicate "keep the original value"? If not, is there some other way to update select, arbitrary columns of multiple rows in one query?

+3  A: 
...
SET name = CASE id
    WHEN 1 THEN 'Jim'
    WHEN 3 THEN 'Precious'
    ELSE name -- defaulting to the value it already has.
...
Wrikken
+3  A: 

I think you would need to add an Else updating it to its original value.

UPDATE person
SET name = CASE id
    WHEN 1 THEN 'Jim'
    WHEN 3 THEN 'Precious'
    ELSE name
END,
sex = CASE id
    WHEN 1 THEN 'female'
    WHEN 2 THEN 'male'
    ELSE sex
END
WHERE id IN (1,2,3)
Martin Smith
Thanks worked like a charm.
dimo414