我一直在为我的 SQL 数据库开发触发器。
表格:
表 1:ID(int,自动增量),value1(varchar),value2(varchar),count(int)
TABLE1_History:ID(与 TABLE1.ID 分开,int,自动增量),与 TABLE1 相同的列,但添加了 TimeStamp(smalldatetime)
编码:
SELECT @@ROWCOUNT FROM TABLE1_History, INSERTED
WHERE TABLE1_History.value1 LIKE INSERTED.value1
AND TABLE1_History.value2 LIKE INSERTED.value2
AND DATEDIFF(HOUR,TABLE1_History."TimeStamp", GETDATE()) > 24;
IF(@@ROWCOUNT = 0)
BEGIN
INSERT INTO TABLE1_History(value1, value2, count, "TimeStamp")
SELECT value1, value2, count, GETDATE() FROM INSERTED
END
ELSE
BEGIN
UPDATE TABLE1_History
SET "TimeStamp" = GETDATE(), count = count+(SELECT count FROM INSERTED)
WHERE TABLE1_History.value1 LIKE (SELECT value1 FROM INSERTED)
AND TABLE1_History.value2 LIKE (SELECT value2 FROM INSERTED)
AND DATEDIFF(HOUR,TABLE1_History."TimeStamp", GETDATE()) < 24;
END
END
应该发生什么:
当我向 TABLE1 添加新行时,我希望 TABLE1_History 更新。
TABLE1_History仅在已存在与新行具有相同 value1&value2 的行并且自添加该行以来已超过 24 小时时才添加新行。
否则,计数器增加。
怎么了:
截至目前:TABLE1_History 每次都会更新。值是否匹配并不重要。
在我决定让 TABLE1_History.ID 与 TABLE1.ID 分开之前,它似乎起作用了。