2013-06-12 109 views
0

我一直在爲我的SQL數據庫開發一個觸發器。我的觸發器不會工作

的表格:

TABLE1:ID(INT,自動增量),值1(VARCHAR),值2(VARCHAR),計數(INT)

TABLE1_History:ID(從TABLE1.ID獨立,INT,自動增量),相同的列TABLE1但具有添加的時間戳(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 ONLY中添加新行如果行已經用相同的值1 &值2作爲新行存在,如果它已經24h以上,因爲加入該行。

否則,計數器增加。

會發生什麼:

截至目前:TABLE1_History得到每一次更新。如果值匹配或不匹配,則無關緊要。

在我決定讓TABLE1_History.ID與TABLE1.ID分開之前,它似乎工作正常。

+0

SQL-Server?請添加標籤。 –

+0

你的意思是在stackoverflow標籤?在那種情況下,是固定的。 –

回答

1

你應該避免使用關鍵字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 
+0

可能比我的解決方案更好。觸發器適用於值相同的情況。但是當他們彼此不同時,不會發生。 –

+0

我現在試圖清空表格,並意識到現在歷史上沒有任何東西被添加 –

+0

@Yoan已修復以允許「新」記錄 –