Dav.id
Dav.id

Reputation: 2797

SQL 2008 R2: Trying to get the T-SQL MERGE statement working in a stored procedure

I have looked at various example of the SQL Merge statement.. all of which look excellent, albeit for some reason I cannot seem to get the correct/expected results from my Merge test.

Quick overview: I have a simple table with some design data in it.. and reading about MERGE seems to point to a more efficient way of doing an 'upsert' (i.e: an Insert or Update depending if the record exists or not).

So the SQL 2008 code goes something like this (sorry if it is not fully complete, as I am working on it!):

This will be in a stored procedure, so the @values are obviously the passed params..

merge designs as ds
using ( select designname, designcode from designs) as dsi
on (@passedDesignName = dsi.designname and @passedDesignCode = dsi.designcode)
when matched then
    update set ds.designname = @passedDesignName, ds.designcode = @passedDesignCode
when not matched then
    insert (designname, designcode)
    values (@passedDesignName, @passedDesignCode)

The issue seems to be out of the 7 records I am testing with, ALL of them seem to be updated, when clearly I can only see one record that matches the update.. and the strange thing is if I pass some NEW data (designname and designcode), I seem to get a repeating insert.. from my last test it seemed 7 new inserts which I am guessing isn't just a fluke..

Hope I have explained this correctly.. part of attacking something new is mostly getting the context correct right?

Thanks in advance for any feedback.

P.S: Sorry, there is a semi-colon at the end of the merge statement! to complete the parse checking/syntax.

Upvotes: 2

Views: 738

Answers (1)

Andomar
Andomar

Reputation: 238078

You're using designs as both the target and the source table:

merge designs as ds
using ( select designname, designcode from designs) as dsi

This is equivalent to:

merge designs as ds
using designs as dsi

Instead, try to pass the variables as the source table:

merge designs as ds
using (
      select  @passedDesignName as designname
      ,       @passedDesignCode as designcode
      ) as dsi
on (ds.esignName = dsi.designname and ds.designCode = dsi.designcode)

Upvotes: 5

Related Questions