In my SQL Server database I want to update columns of multiple rows. I can do it for one row only:
UPDATE theTable
SET theColumn = case
WHEN id = 1 then 'a'
WHEN id = 2 then 'b'
WHEN id = 3 then 'c'
WHERE id in (1, 2, 3)
How can I update more columns (theColumn2, theColumn3…) in the same query?
Best Answer
An example of how this can be done (see SQLFiddle here):
(p.s. I used a CTE (aka the
WITH
clause) and PostgreSQL (I don't use MS SQL Server) but the principles are very much the same - except for theSERIAL
datatype - use MS's auto-incrementing type!).Create and populate a source table (named one):
And also a target table (two):
(double check your values in table two):
And then run your update (multiple columns at a time):
And then re-run your
Again, see the SQLFiddle!
You can also use a
JOIN
to update the target record(s). I would encourage you to experiment with these techniques - very useful!Your first result for two (i.e. inserted values) will look like this:
and your second (updated) result will be: