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

时间:2014-04-28 16:37:15

标签: sql-server date triggers match

我有一个与触发器有关的问题。我有一个表(FoodPrice),其中包含不同的列,如开始日期和到期日期。 让我们考虑一下,我想添加一个可能像销售一样到期的价格,我希望(ON INSERT)将前一个值的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列的重复值不是什么大问题,但可以创建一个触发器来解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:1)

以下是代码:

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

与往常一样,我是在实际更新之前首先测试选择的忠实粉丝,因此是CTE。