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

Updating multiple values at a time

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

Problem

I have been given the task to update a few rows in a database. There are two columns in which one is ID and the other is CURRENCY. I have updated these rows using the update statements that follow:

update account set currency = 'INR' where id =15;
update account set currency = 'EURO' where id =12;
update account set currency = 'DOLLAR' where id =18;
update account set currency = 'Pound' where id =13; 
-- and so on.


Actually, in this case I was able to do it easily using these update statements because of a relatively low number of rows, but what if there are thousands or hundreds of thousands of rows? Is this the only way to update them, or is there any alternate way or script?

Solution

You can use a table constructor with VALUES:

update account 
set currency = nv.currency
from
    ( values
        (12, 'EURO'),
        (18, 'DOLLAR'),
        (13, 'Pound')
    ) as nv (id, currency)
where account.id = nv.id ;

Code Snippets

update account 
set currency = nv.currency
from
    ( values
        (12, 'EURO'),
        (18, 'DOLLAR'),
        (13, 'Pound')
    ) as nv (id, currency)
where account.id = nv.id ;

Context

StackExchange Database Administrators Q#246753, answer score: 16

Revisions (0)

No revisions yet.