I need some help with SQL Server merge statement. I am using version 2008.
I have two tables table1 and table2 with 3 column in each table: name, age, lastname.
I want to do little variant of Upsert from table2 to table1. If record exists in table 1, ignore. If doesn't exist then insert.
I know following would work -
merge into [test].[dbo].[table1] a
using [test].[dbo].[table2] b
on a.name = b.name and a.lastname = b.lastname
when not matched then
insert (name, age, lastname) values (b.name, b.age, b.lastname)
I would like to know if I could do something like this? Currently following doesn't work:
merge into [test].[dbo].[table1] a
using [test].[dbo].[table2] b
on a.name = b.name and a.lastname = b.lastname
when not matched then
insert (select name, max(age), lastname from b group by name, lastname)
Basically I want to insert only 'unique records' from table 2 to table 1. Unique means name and lastname should be same.
Thanks.