sql server-MS sql在插入具有相同名称的值时更改到期日期



我有一个关于触发器的问题。我有一个表(FoodPrice),它有不同的列,比如开始日期和到期日期。让我们考虑一下,我想添加一个可能像销售一样过期的价格,我想(在插入时)将以前值的ExpiryDate设置为当前日期:

初始表格

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

插入行的新表:

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           

Food专栏的重复值不是什么大不了的事,但有可能创建一个触发器来解决这个问题吗?非常感谢。

以下是代码:

-- 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

和往常一样,我非常喜欢在实际更新之前先测试select,从而测试CTE。

最新更新