Sql server MS SQL在插入同名值时更改过期日期

Sql server MS SQL在插入同名值时更改过期日期,sql-server,date,triggers,match,Sql Server,Date,Triggers,Match,我有一个关于触发器的问题。我有一个表FoodPrice,有不同的列,比如开始日期和到期日期。 让我们考虑一下,我想添加一个可能像销售一样过期的价格,我想在INSERT中设置前一个值的到期日期到当前日期: 初始表 Food Value StartDate ExpiryDate ------ ---------- ---------- ---------- Carrot 25.5 24/12/2013 NULL App

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

初始表

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           
食物列的双重值不是什么大问题,但有可能创建一个触发器来解决这个问题吗?谢谢大家!

以下是代码:

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

之前的值到底是多少?按日期?还有,SQL Server的哪个版本?对不起,我的解释不清楚。“previous”是指新插入之前的expireydate值。例如,在新表中,Carrot的“previous”行的值为25.5。胡萝卜的新值是24。这个版本是SQLServer2008R2。它工作起来很有魅力!唯一的问题是我将“inserted”替换为“inserted”。谢谢!对不起,忘记换了。ins是我的辅助表-我总是在一次执行时首先将插入的数据保存到一个实际表中,然后从那里开始处理查询,从而开始编写/修改触发器。