Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid inserting duplicate records from source table while merge?

Tags:

sql

sql-server

I'm into a scenario where I need to download and update a catalog which has codes and its descriptions in it. So I'm trying to import this data into a temp table and do an insert / update to my target table using merge statement but I ended up with an issue where my temp table had duplicate records and the merge statement which I was used inserted duplicate records into the target table.

Example: Temp table has data

   Code   Description
    C1       Desc1
    C2       Desc2
    C1       Desc1    

and I want my target table data as

   Code   Description
    C1       Desc1
    C2       Desc2

I used below merge statement:

 MERGE INTO Frames as Target using Temp as Source
 on Source.Code=Target.Code
 WHEN MATCHED THEN  UPDATE  set Target.Description=Source.Description 
 WHEN NOT MATCHED THEN insert (Code,Description) values (Code,Description);

but finally my target table has data

   Code   Description
    C1       Desc1
    C2       Desc2
    C1       Desc1   

I know this may be a simple query to some of you. But I am not strong in Sql, so expecting some solution for my problem.

Thanks in advance.

like image 808
user2502961 Avatar asked Feb 17 '23 04:02

user2502961


1 Answers

Just don't use Temp directily as Source but filter it for distinct values first

MERGE INTO Frames as Target 
using (SELECT DISTINCT * FROM Temp) as Source
on Source.Code=Target.Code
WHEN MATCHED THEN  UPDATE  set Target.Description=Source.Description 
WHEN NOT MATCHED THEN insert (Code,Description) values (Code,Description);
like image 197
Nenad Zivkovic Avatar answered Feb 18 '23 17:02

Nenad Zivkovic