简体   繁体   中英

SQL Server 2008 MERGE with Target as table with no values

I want to do MERGE from a source to a Target where I insert rows if they don't exist and update the ones that do. When I do this, I get only inserts... no updates. I read this post (http://stackoverflow.com/questions/5015623/merge-query-in-sql-server-2008), which is a bit confusing for me to follow, but it seems that I need a duplicate source to make this happen. Can someone explain why a DUPLICATE source would be required? I just don't get it, especially which keys I should be using (duplicate source or regular ones)-- Maybe the duplicate SourceTable is just not needed?

here my (simplified) SourceTable :

   row   userid   placervalue   placerDt
   ---   -------  ----------    ----------
   1     abc      a1            1/1/12
   2     xyz      b1            1/1/12
   3     abc      b2            1/20/12
   etc.

and my target TargetTable that is same, but currently with no rows in it.

   row   userid   placerId   
   ---   -------  ----------
  (nothing loaded yet)

what I want is to INSERT rows that are NOT in the target, and UPDATE rows that are.

   row   userid   placervalue   placerDt
   ---   -------  ----------    ----------
   1     abc      a1            1/20/12  *** note change here (row 3 updates row 1)
   2     xyz      b1            1/1/12

When I run this code, I get only inserts (would also like to know why)

MERGE TargetTable as t
USING SourceTable as s
   ON s.userid = t.usrid AND s.placervalue = t.placervalue
WHEN MATCHED THEN
   UPDATE
      SET t.placerDt = s.placerDt
WHEN NOT MATCHED THEN
   INSERT (
       userid
     , placerid
     , placerDt
   ) VALUES (
       s.userid
     , s.placerid
     , s.placerDt
   );

If you dont have rows on your destination table, there is nothing to MATCH, that's why you only get inserts.

Run the query a second time that you should have updates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM