0

我一直在为我的 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 分开之前,它似乎起作用了。

4

1 回答 1

1

你应该避免使用关键字 so TimeStamp。如果你能把它改成LastModified什么的

不要使用@@ROWCOUNT,你可以加入INSERTED,我不确定你为什么使用LIKE。尝试这个

IF NOT( EXISTS (   -- if it's not already in the table
    SELECT value1 FROM TABLE1_History
    JOIN INSERTED ON TABLE1_History.value1 = INSERTED.value1
                 AND TABLE1_History.value2 = INSERTED.value2
   ) )
   OR EXISTS (    -- or its history was last modified over 24 hours ago
    SELECT value1 FROM TABLE1_History
    JOIN INSERTED ON TABLE1_History.value1 = INSERTED.value1
                 AND TABLE1_History.value2 = INSERTED.value2
                 AND DATEDIFF(HOUR,TABLE1_History."TimeStamp", GETDATE()) > 24
   )       
BEGIN             -- insert it into the history table
    INSERT INTO TABLE1_History(value1, value2, count, "TimeStamp")
    SELECT value1, value2, count, GETDATE() FROM INSERTED
END
ELSE
BEGIN             -- otherwise update the current history record
    UPDATE th
    SET th."TimeStamp" = GETDATE()
        , th.count = th.count + INSERTED.count
    FROM TABLE1_History th
    JOIN INSERTED ON th.value1 = INSERTED.value1
                 AND th.value2 = INSERTED.value2
                 AND DATEDIFF(HOUR, th."TimeStamp", GETDATE()) < 24;
END
于 2013-06-12T13:27:17.117 回答