How can i update multiple records in a single statement like this with SQL?:
UPDATE records
SET name='abc' where id=3,
SET name='def' where id=1
In SQL, sometimes we need to update multiple records in a single query. We will use the UPDATE keyword to achieve this. For this, we use 2 kinds of examples i.e. the first based on only one condition and the second based on multiple conditions.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...
Standard SQL:2003 syntax (works on SQL Server 2008 onwards):
MERGE INTO records
USING (
VALUES (1, 'def'),
(3, 'abc')
) AS T (id, name)
ON records.id = T.id
WHEN MATCHED THEN
UPDATE
SET name = T.name;
Note that NAME
and RECORDS
are SQL reserved words.
For just a few records, you could use:
update records
set name = case id
when 1 then 'def'
when 3 then 'abc'
end
where id in (1, 3)
A bit more flexible is to create a result that you can join into the update:
update r
set name = x.name
from records r
inner join (
select id = 1, name = 'abc' union all
select 3, 'def' union all
select 4, 'qwe' union all
select 6, 'rty'
) x on x.id = r.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With