我的触发器有点问题。它应该:
- 更新我的主表中插入的历史表并添加时间戳。
- 如果历史表中的一行已经具有相同的值,则不应添加任何内容,但应增加计数器并更新时间。
- 如果距离上次更新超过 24 小时,将创建一个新行。
马虎的伪代码:
IF NOT EXISTS ( --if the value isn't in the history table
SELECT History.value1 FROM History, INSERTED
WHERE History.value1 LIKE INSERTED.value1
AND History.value2 LIKE INSERTED.value2
)
OR EXISTS ( --or if it has been added over 24h ago
SELECT History.value1 FROM History, INSERTED
WHERE History.value1 LIKE INSERTED.value1
AND History.value2 LIKE INSERTED.value2
AND DATEDIFF(HOUR,History.time, GETDATE()) > 24
)
BEGIN --Insert it
INSERT INTO History(value1, value2, counter, time)
SELECT value1, value2, counter GETDATE() FROM INSERTED
END
ELSE
BEGIN -- else, increase counter and add new time
UPDATE History
SET History.time = GETDATE(),
History.Items = History.Items + INSERTED.Items
FROM History
JOIN INSERTED ON History.value1 = INSERTED.value1
AND History.value2 = INSERTED.value2
AND DATEDIFF(HOUR, _History.time, GETDATE()) < 24;
END
示例表:
__________________________________________________
| value1 | value2 | counter | time(last updated) |
+------------------------------------------------+
| test1 | test2 | 1 | < 24h |
| test3 | test4 | 1 | > 24h |
| test3 | test4 | 1 | < 24h |
+------------------------------------------------+
输入:
INSERT INTO main_table(value1, value2, counter)
VALUES ('test3', 'test4', 1);
结果表:
__________________________________________________
| value1 | value2 | counter | time(last updated) |
+------------------------------------------------+
| test1 | test2 | 1 | < 24h |
| test3 | test4 | 1 | > 24h |
| test3 | test4 | 1 | < 24h | <--This counter+time should be updated
| test3 | test4 | 1 | < 24h | <--This row shouldn't be added
+------------------------------------------------+
我理解为什么会发生这种情况(因为代码找到了超过 24 小时的历史值,而忽略了较新的值),但我不知道如何修复它。