我想在插入和更新后创建一个触发器,该触发器计算多行中的值总和并在[Target_Cummlative]
中设置总和。我尝试以下代码,但这会导致此错误:
第156条消息,级别15,状态1,过程target_cummlative,第13行
”附近的语法不正确
关键字“ FROM
我的代码:
CREATE TRIGGER [dbo].[target_cummlative]
ON [dbo].[Appointments]
AFTER insert, UPDATE
AS
BEGIN
IF TRIGGER_NESTLEVEL() > 1
RETURN
UPDATE T1
SET t1.[Target_Cummlative] = SUM(ISNULL(CAST([TARGET] AS FLOAT), 0)
FROM [Appointments] T1
INNER JOIN inserted i ON T1.[UniqueId] = i.[UniqueId]
GROUP BY CONVERT(VARCHAR(10), t1.[StartDate], 111), t1.[ResourceId]
END
这是我目前拥有的,如您所见Target cummlative
为空
Id StartDate Location ResourceId TARGET Target_Cummlative
1381 2019-07-22 07:00:00 41051 1 20 NULL
1382 2019-07-22 08:00:00 41051 1 20 NULL
1383 2019-07-22 09:15:00 41051 1 15 NULL
1384 2019-07-22 10:00:00 41051 1 20 NULL
1385 2019-07-22 11:00:00 41051 1 20 NULL
1386 2019-07-22 12:30:00 41051 1 8 NULL
我要设置TARGET
列中的值的总和,并将Target cummlative
更新为
Id StartDate Location ResourceId TARGET Target_Cummlative
1381 2019-07-22 07:00:00 41051 1 20 103
1382 2019-07-22 08:00:00 41051 1 20 103
1383 2019-07-22 09:15:00 41051 1 15 103
1384 2019-07-22 10:00:00 41051 1 20 103
1385 2019-07-22 11:00:00 41051 1 20 103
1386 2019-07-22 12:30:00 41051 1 8 103
答案 0 :(得分:1)
如果可能的话-我建议不要在同一表中存储累积数据-最好创建一个单独的表来存储汇总信息。
无论如何-您的问题在SET
子句中缺少括号。
CREATE TRIGGER [dbo].[target_cumulative]
ON [dbo].[Appointments]
AFTER insert, UPDATE
AS
BEGIN
IF TRIGGER_NESTLEVEL() > 1
RETURN
UPDATE T1
SET T1.[Target_Cumulative] = SUM(ISNULL(CAST([TARGET] AS FLOAT), 0))
FROM dbo.Appointments AS T1
INNER JOIN inserted AS ION I.UniqueId = T1.UniqueId
GROUP BY CONVERT(DATE, T1.StartDate), T1.ResourceId;
END;
哦-累积中有错字,应该是累积