All articles

SQL Server UPSERT variációk 5.

Published 2008-06-04 - Last modified 2008-06-04

Az upsertes vizsgálódásunk utolsó része jön, ebben az új SQL Server 2008 MERGE parancsot használjuk:

create proc dbo.UpsertClient5
  @id int,
  @name nvarchar(100)
as
merge dbo.Client u
using (select * from (values (@id, @name)) t(id, name)) t
on u.id = t.id
when matched then update set u.name = t.name
when not matched then insert(id, name) values(t.id, t.name);

Elegáns, szép, és a harmadik megoldáshoz hasonlóan itt is jöhetne be több sor is, tábla típusú paraméterként. Nincs explicit tranzakciókezelés, mert belül a parancs eleve tranzakcionális, mint minden DML parancs.
Nem biztos, hogy ezzel meggyőztem bárkit is a mergeről, hisz ez csak egy apró alkalmazása, de érdemes mindig szem előtt tartani, hogy most már nem csak insert, update, delete van, hanem merge is.