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.
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With