HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to update multiple columns of multiple rows in one SQL statement

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
rowsupdatecolumnsstatementsqlonemultiplehow

Problem

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?

Solution

You could supply the new values as a table (with the help of the VALUES row constructor), so that you could join it with the target table and use the join in the UPDATE statement, like this:

UPDATE
  tgt
SET
  Column1 = src.Column1,
  Column2 = src.Column2,
  Column3 = src.Column3,
  ...
FROM
  dbo.TargetTable AS tgt
  INNER JOIN
  (
    VALUES
    (1, 'a', 'k', 'x', ...),
    (2, 'b', 'l', 'y', ...),
    (3, 'c', 'm', 'z', ...)
  ) AS src (ID, Column1, Column2, Column3, ...)
    ON tgt.ID = src.ID
;

Code Snippets

UPDATE
  tgt
SET
  Column1 = src.Column1,
  Column2 = src.Column2,
  Column3 = src.Column3,
  ...
FROM
  dbo.TargetTable AS tgt
  INNER JOIN
  (
    VALUES
    (1, 'a', 'k', 'x', ...),
    (2, 'b', 'l', 'y', ...),
    (3, 'c', 'm', 'z', ...)
  ) AS src (ID, Column1, Column2, Column3, ...)
    ON tgt.ID = src.ID
;

Context

StackExchange Database Administrators Q#186147, answer score: 5

Revisions (0)

No revisions yet.