sqlschool.gr logo

articles

Articles of SQLschool.gr Team

What you need to know when using MERGE statement

Antonios Chatzipavlis
Monday 13 January 2020

Στο SQL Server 2008 παρουσιάστηκε για πρώτη φορά το MERGE statement το οποίο απλοποιούσε τις διαδικασίες insert/update/delete ιδιαίτερα σε ETL διαδικασίες και από όσο έχω δει έχει αγαπηθεί από αρκετούς και μέσα σε αυτούς είμαι και εγώ.

Όμως πρέπει να γνωρίζουμε κάποια πράγματα που αφορούν την συμπεριφορά του καθώς έχει και αυτό τις ιδιαιτερότητες του τις οποίες θα σας παρουσιάσω στο άρθρο αυτό.

Αρχικά να τονίσω ότι είναι atomic statement αυτό σημαίνει ότι ή θα γίνουν όλα ή τίποτα όμως έχει ιδιαιτερότητες όσον αφορά το concurrency που προσφέρει καθώς μπορεί εύκολα να έχουμε καταστάσεις που ονομάζονται race conditions.

Αρχικά με το step-1 του παρακάτω script ας δημιουργήσουμε μια sample database και κάποιους πίνακες με την λογική ότι ο S είναι αυτός που θα έχεις τις εγγραφές που θέλουμε να ενημερώσουν τον T.

Το πρώτο πράγμα που πρέπει να καταλάβουμε είναι ότι αν η ίδια εντολή εκτελεστεί από δύο διαφορετικά sessions ταυτόχρονα θα έχουμε race conditions ή primary key conflicts. Αν για παράδειγμα εκτελέσουμε το step-2a σύντομα θα έχουμε primary key violations και αν δεν έχουμε βάλει error handler τότε ….

Για να διασφαλίσουμε τέτοιες περιπτώσεις θα πρέπει να χρησιμοποιούμε ισχυρότερο isolation level όπως SERIALIZABLE ή το HOLDLOCK table hind όπως στο step-2b.

Στο step-4 ας βάλουμε κάποιες εγγραφές στο πίνακα S, και ας εκτελέσουμε την MERGE για να ενημερώσουμε τον Τ όπου φυσικά όλα θα κυλήσουν ομαλά.

Αν στο πίνακα S βάλουμε ακόμα μια φορά τα ίδια δεδομένα χωρίς να έχουμε σβήσει τα προηγούμενα (step-5) θα πάρουμε το εξής λάθος

Msg 8672, Level 16, State 1, Line 79
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

Αν τώρα (step-6) ο πίνακας S έχει διπλές εγγραφές και εκτελέσουμε την merge τότε θα πάρουμε το λάθος

Msg 2627, Level 14, State 1, Line 96
Violation of PRIMARY KEY constraint 'PK__t__357D0D3EB1FFFDF3'. Cannot insert duplicate key in object 'dbo.t'. The duplicate key value is (1).

Να επισημανθεί ότι στις δύο τελευταίες περιπτώσεις χρησιμοποιείται holdlock table hint. Αλλά ο S περιέχει διπλές εγγραφές για αυτό είναι σκόπιμο να γίνεται group by ή distinct.

Αυτές είναι κάποιες περιπτώσεις που πρέπει κάποιος να γνωρίζει όταν χρησιμοποιεί την MERGE.


-- step 1

create database mergedemo;
go

use mergedemo;
go

create table s (col1 int, col2 nchar(10));
create table t (col1 int primary key, col2 nchar(10));
go

-- step 2a

set nocount on;
while 1=1
begin
    declare
            @col1 int = checksum(sysdatetime()),
            @col2 nchar(10) = N'sqlschool'; 

    merge into t
    using ( values( @col1, @col2) ) as s ( col1, col2 )
        on t.col1 = s.col1
    when matched then update
        set t.col2 = s.col2
    when not matched then insert
        values( s.col1,s.col2 );
  
end;
set nocount off;


-- step 2b

set nocount on;
while 1=1
begin
    declare
            @col1 int = checksum(sysdatetime()),
            @col2 nchar(10) = N'sqlschool'; 

    merge into t with(holdlock)
    using ( values( @col1, @col2) ) as s ( col1, col2 )
        on t.col1 = s.col1
    when matched then update
        set t.col2 = s.col2
    when not matched then insert
        values( s.col1,s.col2 );
  
end;
set nocount off;



-- step 4

truncate table s;
truncate table t;

insert into S values (1,'a'),(2,'b'),(3,'c');
select * from S;

merge into t with(holdlock)
    using s on t.col1 = s.col1
    when matched then update
        set t.col2 = s.col2
    when not matched then insert
        values( s.col1,s.col2 );

select * from t;


-- step 5

insert into S values (1,'a'),(2,'b'),(3,'c');
select * from S;

merge into t with(holdlock)
    using s on t.col1 = s.col1
    when matched then update
        set t.col2 = s.col2
    when not matched then insert
        values( s.col1,s.col2 );

select * from t;

-- step 6

truncate table s;
truncate table t;

insert into S values (1,'a'),(2,'b'),(3,'c'),(1,'d');
select * from S;

merge into t with(holdlock)
    using s on t.col1 = s.col1
    when matched then update
        set t.col2 = s.col2
    when not matched then insert
        values( s.col1,s.col2 );

select * from t;



//Antonios Chatzipavlis

Antonios Chatzipavlis

Antonios Chatzipavlis

Antonios Chatzipavlis is a highly experienced Data Solutions Consultant and Trainer. He has been working in the IT industry since 1988, holding various roles such as senior developer, IT Manager, Data & AI Solutions Architect and Consultant.

Since 1995, Antonios has focused on modern technologies and software development tools, primarily by Microsoft. He has specialized in Data & AI since 2000, with expertise in Microsoft Data Platform (SQL Server, Azure SQL Databases, Azure Synapse Analytics, Microsoft Fabric, Power BI, AI) and Databricks.

Antonios is also a Microsoft Certified Trainer (MCT) for over 25 years, has been recognized as a Microsoft Most Valuable Professional (MVP) in Data Platform since 2010 and he is in the Data Expert 40 Powerlist 2024 by Boussias. He is the co-founder and visionary behind XLYTiCA, a company dedicated to Data & AI solutions.

Episode

Task Flows in Microsoft Fabric

image

More Episodes...

Tip

Get Certified: Become a Fabric Data Engineer

More Tips...

Become a member

If you want to receive updates from us become a member to our community.

Connect

Explore

Learn

sqlschool.gr © 2010-2025 All rights reserved

This site uses cookies for operational and analytics purposes only. By continuing to browse this site, you agree to their use.