Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update multiple rows in oracle

Tags:

sql

oracle

I would like to update multiple rows with different values for all different records, but don't have any idea how to do that, i am using below sql to update for single record but i have 200 plus records to update

update employee
set staff_no = 'ab123'
where depno = 1

i have 50 dep and within those dep i need to update 200 plus staff no. any idea. At the moment if i just do a

 select * from Departments 

i can see list of all employee which needs staff no updating.

UPDATE person
   SET staff_no = 
       CASE person_no
            WHEN 112 THEN 'ab123'
            WHEN 223 THEN 'ab324'
            WHEN 2343 THEN 'asb324'
            and so on.....


       END
like image 641
srk786 Avatar asked Feb 19 '15 14:02

srk786


People also ask

Can I update multiple rows in Oracle?

Best Answer Ya. It can be done. Check this. 22222222 02-JAN-14 500 TRFC 4 1 10 rows selected.

How do I update multiple rows at once?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);

How do you update multiple rows in a column?

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.

How can I update multiple values in one column in Oracle?

First, you specify the name of the table which you want to update. Second, you specify the name of the column whose values are to be updated and the new value. If you update more than two columns, you separate each expression column = value by a comma.


2 Answers

You should be able to use MERGE statement to do it in a single shot. However, the statement is going to be rather large:

MERGE INTO employee e
USING (
   SELECT 1 as d_id, 'cd234' as staff_no FROM Dual
       UNION ALL
   SELECT 2 as d_id, 'ef345' as staff_no FROM Dual
       UNION ALL
   SELECT 3 as d_id, 'fg456' as staff_no FROM Dual
       UNION ALL
   ... -- More selects go here
   SELECT 200 as d_id, 'za978' as staff_no FROM Dual
) s
ON (e.depno = S.d_id)
WHEN MATCHED THEN UPDATE SET e.staff_no= s.staff_no
like image 51
Sergey Kalinichenko Avatar answered Sep 30 '22 22:09

Sergey Kalinichenko


use a case expression

UPDATE employee
   SET staff_no = 
           CASE depno
                WHEN 1 THEN 'ab123'
                WHEN 2 THEN 'ab321'
                --...
                ELSE staff_no
           END
 WHERE depno IN ( 1, 2 ) -- list all cases here. use a subquery if you don't want to / cannot enumerate 
like image 44
collapsar Avatar answered Sep 30 '22 22:09

collapsar