How to Update, Insert, Delete in one MERGE query in Sql Server 2008? -


i have 2 tables - source , destination. merge source destination using merge query (sql server 2008).

my setup follows:

  1. each destination record has 3 fields (in real application there more 3, of course) - id, checksum , timestamp.
  2. each source record has 2 fields - id , checksum.
  3. a source record inserted destination if there no destination record same id.
  4. a destination record updated source record same id provided source record checksum not null. guaranteed if checksum not null different respective destination checksum. given.
  5. a destination record deleted if there no source record same id.

this setup should lend quite merge statement semantics, yet unable implement it.

my poor attempt documented in sql fiddle

what doing wrong?

edit

btw, not merge based solution here.

create table #destination (id int,[checksum] int,[timestamp] datetime) create table #source (id int,[checksum] int)  insert #destination values(1,1,'1/1/2001'),(2,2,'2/2/2002'),(3,3,getdate()),(4,4,'4/4/2044') insert #source values(1,11),(2,null),(4,44);  merge #destination d using #source s on (d.id=s.id) when not matched target  insert(id,[checksum],[timestamp]) values(s.id,s.[checksum],getdate()) when matched , s.[checksum] not null update set d.[checksum]=s.[checksum], d.[timestamp]=getdate() when not matched source delete output $action, inserted.*,deleted.*;  select * #destination 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -