Wednesday, 10 September 2014

Simple Oracle's Merge statement[example]

step 1: Create two tables [EXAM and REEXAM] and insert                   values


insert all into exam(ROLLNO,SCORE) VALUES(111,80)
               into exam(ROLLNO,SCORE) VALUES(112,null)
               into exam(ROLLNO,SCORE) VALUES(113,68)
               into exam(ROLLNO,SCORE) VALUES(114,72)
               into exam(ROLLNO,SCORE) VALUES(115,null)
               into exam(ROLLNO,SCORE) VALUES(116,89)
               into exam(ROLLNO,SCORE) VALUES(117,76)
               into exam(ROLLNO,SCORE) VALUES(118,null)
               into exam(ROLLNO,SCORE) VALUES(119,null)
select * from dual;

EXAM table: 

ROLLNO
SCORE          
111
80
112
(Null)
113
68
114
72
115
(Null)
116
89
117
76
118
(Null)
119
(Null)

INSERT all INTO REEXAM(ROLLNO,SCORE)VALUES(112,77)
                    INTO REEXAM(ROLLNO,SCORE)VALUES(115,67)
                    INTO REEXAM(ROLLNO,SCORE)VALUES(118,58)
                    INTO REEXAM(ROLLNO,SCORE)VALUES(119,83)
SELECT * FROM dual;

REEXAM table:

ROLLNO
SCORE
112        
76
115
94
118
82
119
58

step 2: Merge tables

 MERGE INTO exam a USING (SELECT ROLLNO,score FROM reexam) b on (a.rollno=b.rollno)
  when MATCHED then UPDATE set a.score=b.score;

ROLLNO
SCORE
111        
80
112        
76
113        
68
114        
72
115        
94
116        
89
117        
76
118        
82
119        
58
4 rows merged.

No comments:

Post a Comment