Skip to Content
author's profile photo Former Member
Former Member

counting inserts/updates when doing a merge

When doing a merge statement we'd like to log the number of rows inserted and the number of rows updated.

At present we do this using 2 separate statements so we know from @@rowcount how many rows each one has operated on.

Is there anyway of getting the individual counts from a merge statement ?

Thanks

Add a comment
10|10000 characters needed characters exceeded

Related questions

1 Answer

  • Posted on Oct 14, 2015 at 06:48 PM

    Interesting question. Here is one way I can think to do it:

    declare @minserts int, @mupdates int
    

    set @minserts = 0

    set @mupdates = 0

    merge into myhist as h

    using mytrans as t

    on h.pkey = t.pkey

    when matched then update set h.description = t.description, @mupdates = @mupdates + 1

    when not matched then insert (pkey,description) values (t.pkey,t.description)

    select @minserts = @@rowcount - @mupdates

    print "UPDATES: %1! INSERTS: %2!",@mupdates,@minserts

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.