Question

I have a question relating to trigger. I have a table (FoodPrice) with different columns like a start date and an expiry date. Let's consider that I would like to add a price that could expire like a sale, I would like (ON INSERT) to set the ExpiryDate of the previous value to the current date:

Initial table

Food      Value         StartDate     ExpiryDate
------    ----------    ----------    ----------
Carrot    25.5          24/12/2013    NULL
Apple     44.9          5/1/2014      NULL
Squash    25.6          12/3/2013     NULL

New table with inserted rows:

Food      Value         StartDate     ExpiryDate
------    ----------    ----------    ----------
Carrot    25.5          24/12/2013    28/4/2014
Apple     44.9          5/1/2014      NULL
Squash    25.6          12/3/2013     28/4/2014
Carrot    24            28/4/2014     NULL
Squash    22            28/4/2014     NULL           

Dupplicate values for Food column is not a big deal but is it possible to create a trigger to solve this problem ? Thank you !

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top