2015-10-05 86 views
0

我試圖實現自動時間戳更新,當某些設備的狀態更改。 我有這樣的設備的表:Sqlite觸發器不起作用

CREATE TABLE devices(
    id int PRIMARY KEY, 
    status text, 
    "timestamp" datetime, 
    FOREIGN KEY (timestamp) REFERENCES timestamps (controls) 
); 

這是時間戳表:

CREATE TABLE timestamps (
    "database" datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP), 
    controls datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP) 
); 

當我嘗試這個觸發,並在devices表修改行status列,我不看到timestamps表中的任何更改(特別是它是空白的)。

CREATE TRIGGER update_timestamps UPDATE OF status ON devices 
BEGIN 
    UPDATE timestamps SET controls=datetime('now'); 
END; 

請問你看看有什麼問題嗎?

回答

0

您可能在時間戳表中沒有任何記錄。觸發器確實按需要工作。請參見下面的輸出:

sqlite> CREATE TABLE devices(
    ...> id int PRIMARY KEY, 
    ...> status text, 
    ...> "timestamp" datetime, 
    ...> FOREIGN KEY (timestamp) REFERENCES timestamps (controls) 
    ...>); 

sqlite> CREATE TABLE timestamps (
    ...> "database" datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP), 
    ...> controls datetime NOT NULL DEFAULT(CURRENT_TIMESTAMP) 
    ...>); 

sqlite> CREATE TRIGGER update_timestamps UPDATE OF status ON devices 
    ...> BEGIN 
    ...> UPDATE timestamps SET controls=datetime('now'); 
    ...> END; 
sqlite> 

將數據插入裝置和時間戳表

sqlite> insert into devices (status, "timestamp") values ('test',' 2011-05-05'); 
sqlite> select * from devices; 
|test| 2011-05-05 
sqlite> 
sqlite> insert into timestamps values ('2010-01-01', '2010-01-01'); 
sqlite> select * from timestamps; 
2010-01-01|2010-01-01 

執行更新和通知觸發改變的時間戳數據;

sqlite> 
sqlite> update devices set status = 'test1'; 
sqlite> 
sqlite> select * from devices; 
|test1| 2011-05-05 
sqlite> select * from timestamps; 
2010-01-01|2015-10-05 20:47:05 

你可以插入,而不是在觸發做一個更新,像這樣的數據:

sqlite> create trigger insert_data_into_timestsamp update of status on devices 
    ...> begin 
    ...> insert into timestamps values (datetime('now'), datetime('now')); 
    ...> end; 
sqlite> 
sqlite> select * from devices; 
|test1| 2011-05-05 
sqlite> select * from timestamps; 
2010-01-01|2015-10-05 20:47:05 
sqlite> 
sqlite> drop trigger update_timestamps; 

讓我們更新狀態3倍

sqlite> update devices set status = 'test'; 
sqlite> update devices set status = 'test1'; 
sqlite> update devices set status = 'test2'; 

注意,輸入了3條

sqlite> select * from timestamps; 
2010-01-01|2015-10-05 20:47:05 
2015-10-05 20:50:20|2015-10-05 20:50:20 
2015-10-05 20:50:25|2015-10-05 20:50:25 
2015-10-05 20:50:26|2015-10-05 20:50:26 
+0

但爲什麼沒有時間戳?我爲那些列指定了'DEFAULT CURRENT_TIMESTAMP' – rightaway717

+0

好問題。 'DEFAULT CURRENT_TIMESTAMP'意味着當你執行'INSERT'時,如果沒有爲該列提供數據,將使用當前時間戳。 – zedfoxus

+0

對於我來說,仍然不清楚,因爲你注意到'當前時間戳將被使用',所以我希望sqlite自己將當前時間插入到列中。這是不正確的? – rightaway717