Friday, March 03, 2017

Merge SQL

Posted by AnithaKamatchi on Friday, March 03, 2017 in | No comments

Usage : 

Merging tables - Update the existing rows and insert the new rows in base table from new table

How the Merge SQL works????

Consider two tables "Student_List" and "Student_New"  as shown below
















Case :
Merge the table "Student_New" with "Student_List"

Syntax:
Merge into <base_table_name>
using <new_table_name>
on <condition>
when matched then
<update_query>
when not matched then
<insert_query>

Sample Query:

Merge into Student_List A
using Student_New B
on (A.student_id = B.student_id and 
      A.student_name = B.student_name)
when matched then
update set A.student_age = B.student_age 
                ,A.student_grade = B.student_grade
                 ,A.skills = B.skills
when not matched then
insert (A.student_id,A.student_name,A.student_age,
           A.student_grade,A.skills)
values(B.student_id,B.student_name,B.student_age,
            B.student_grade,B.skills)

Result:          


0 comments:

Post a Comment