Meghana M

Meghana M

  • 1.6k
  • 175
  • 23.3k

SQL query for inserting rows into table if not exist

Dec 19 2023 8:16 AM

Need to read from the employee table and insert into Location table only 1 row if column is having duplicate value 

Eg:Employee table 

  ABC ,1234 , Pavithra p    

  ABC , 4567, Madhu

  BCD ,8910 ,Pavithra Shiva   

  BCD ,111213, Chaitra

 ABCEF , 124567,Priya

Excepted output: Location table

  ABC ,1234 , Pavithra p    

   BCD ,8910 ,Pavithra Shiva   

   ABCEF , 124567,Priya

 

How to add this condition in an existing query

merge into Location as loc using (select e.Id, e.No, ln.Name from Employee e
               inner join Locationname as ln on e.locationcode=ln.LocationId and 
               e.emploc=ln.LocId where e.Id is not null ) as emp on loc.id=emp.id
   when not matched then
            INSERT (Id,No,Name) values(emp.id, emp.no, emp.name);

 


Answers (3)