I need to write an SQL instruction (not a procedure) that updates a date column AND insert the line if an ID is already present in target.
Target table:
ID DT_DEBVAL DT_FINVAL
1 2021-09-01 2050-12-31
2 2021-09-01 2050-12-31
New incoming data:
ID DT_DEBVAL DT_FINVAL
2 2021-09-08 2050-12-31
3 2021-09-08 2050-12-31
4 2021-09-08 2050-12-31
Desired output:
ID DT_DEBVAL DT_FINVAL
1 2021-09-01 2050-12-31
2 2021-09-01 2021-09-07 -- current date minus 1 day
2 2021-09-08 2050-12-31
3 2021-09-08 2050-12-31
4 2021-09-08 2050-12-31
I did same thing as here. This is my version of code:
insert into t1 (id, DT_DEBVAL, DT_FINVAL)
select t.id, t.DT_DEBVAL, t.DT_FINVAL from (
merge t1 As Target
using (select * from t2) AS Source
on Target.id=Source.id and Target.dt_finval=Source.dt_finval
when matched then
update set Target.DT_FINVAL=DATEADD(day, -1, getdate())
when not matched by target then insert (id, dt_debval, dt_finval) values (Source.id, Source.dt_debval, Source.dt_finval) OUTPUT $ACTION as Act, Inserted.* ) t
where t.Act = 'Update'
select * from t1;
And This is obtained output:
ID DT_DEBVAL DT_FINVAL
1 2021-09-01 2050-12-31
2 2021-09-01 2021-09-07
2 2021-09-01 2021-09-07
3 2021-09-08 2050-12-31
4 2021-09-08 2050-12-31
As you can see, lines with ID=2 are not entirely correct. Any idea about why is it reacting this way?