Sqlite触发器无法正常工作

时间:2015-10-05 20:28:46

标签: sql sqlite triggers timestamp

当某些设备的状态发生变化时,我正在尝试实现自动时间戳更新。 我有一个这样的表用于设备:

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)
);

当我尝试此触发器并修改status表中的行devices列时,我在timestamps表中看不到任何更改(特别是它是空白的)

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

你能看看它有什么问题吗?

1 个答案:

答案 0 :(得分: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