Here's the code:
-- the table and sample data
create table FoodPrice (
Food varchar(10),
Value decimal(5,2),
StartDate date,
ExpiryDate date
);
go
insert FoodPrice values
('Carrot', 20, '20131124' , '20131224'),
('Apple' , 40, '20140101' , '20140105'),
('Squash', 25, '20130301' , '20130312'),
('Carrot', 25.5, '20131224' , NULL),
('Apple' , 44.9, '20140105' , NULL),
('Squash', 25.6, '20130312' , NULL)
go
-- the trigger
create trigger trFoodPrice_insert
on FoodPrice
after insert
as
;with x as (
select fp.food, fp.startdate as fp_startdate, fp.expirydate as fp_expirydate,
ins.startdate as ins_startdate, ins.expirydate as ins_expirydate,
row_number() over(partition by fp.food order by fp.startdate) as rn
from ins
inner join foodprice fp on ins.food=fp.food
and fp.startdate < ins.startdate
and fp.expirydate is null
),
y as (
select *
from x
where rn = 1
)
--select * from y
update y
set fp_expirydate = ins_startdate
go
-- let's test it
insert foodprice values
('Carrot', 24, '20140428', null),
('Squash', 22, '20140428', null)
go
select * from
foodprice
order by food, startdate
As always, I'm a big fan of first testing the select before the actual update, hence the CTE.