Let's say I have a table with a compound primary key:
create table FooBar (
fooId int not null,
barId int not null,
status varchar(20) not null,
lastModified datetime not null,
constraint PK_FooBar primary key (fooId, barId)
);
Now I have some tabular data for a particular fooId
, maybe something like this:
1, 1, 'ACTIVE'
1, 2, 'INACTIVE'
...and I want to make a MERGE statement that treats this tabular data as authoritative for fooId
1 only, removing any non-matching records in FooBar
that are for fooId
1, but leaving all records with a fooId
that is not 1 alone.
For example, let's say the FooBar
table currently has this data:
1, 1, 'ACTIVE', ... (some date, not typing it out)
2, 1, 'ACTIVE', ...
1, 3, 'INACTIVE', ...
2, 2, 'INACTIVE'
I would want to run a merge statement with the two datasets mentioned above, and the resultant data set in FooBar
should look like:
1, 1, 'ACTIVE', ...
2, 1, 'ACTIVE', ...
1, 2, 'INACTIVE', ...
2, 2, 'INACTIVE', ...
I would want the row 1, 3, 'INACTIVE'
to be deleted, and the 1, 1, 'ACTIVE'
row to be updated with the new modified timestamp, and the 1, 2, 'INACTIVE'
row to be inserted. I would also like the records for fooId
of 2 to be unmodified.
Can this be done in a single statement? If so, how?