触发从另一个表中插入“SELECT SUM”表

时间:2017-02-13 18:51:17

标签: sql sql-server-2005 triggers

我有这两张桌子:

.

表AUX中的数据具有重复日期,表a必须具有没有重复的日期,但是添加重复日期的总数。

EJ。 05/01/2017 = 123 + 123 + 123。

我认为当一个辅助表中的数据有新数据时,触发器应该可以完成这项工作。

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER [dbo].[trgAfterInsert] ON [dbo].[Table_a_aux] 
After Insert
AS
BEGIN

Declare @dDate as Date;
Declare @iTotal as int;

Select 
    @dDate = i.[date],
    @iTotal = i.total
From inserted i;


IF EXISTS (Select [date] from Table_a where [date] = @dDate) 
BEGIN
Update Table_a 
    SET total = total + @iTotal
WHERE
    [date] = @dDate
END
ELSE 
BEGIN
INSERT INTO Table_a ([date],total) Values (@dDate,@iTotal)
END