sqlite,当表达到MAX记录数时触发

时间:2011-12-06 16:00:56

标签: sql database sqlite triggers

是否可以在sqlite3中添加触发器,以便在表达到最大记录数时删除N(较旧的,或至少是满足过滤器的行)?如果有,怎么样?

简单示例:日志数据库最多包含1000个条目。插入第1000个条目时 前100个被删除。这样我们就可以在达到一定的尺寸后环绕。

敲铃?

1 个答案:

答案 0 :(得分:2)

使用名为bookkeepings

的帮助程序表,这对我有用
create table bookkeepings (bk_name text primary key, bk_value integer not null);

insert or replace into bookkeepings values ('Max Entries', 50);
insert or replace into bookkeepings values ('Qty Entries', 0);

create trigger log_entries_limit_trigger before insert on log_entries
  for each row
  when (select bk_value from bookkeepings where bk_name = 'Qty Entries')
    >= (select bk_value from bookkeepings where bk_name = 'Max Entries')
  begin
    delete from log_entries
      where timestamp = (select timestamp from log_entries order by timestamp limit 1);
  end;

create trigger log_entries_count_insert_trigger after insert on log_entries
  for each row
  begin
    update bookkeepings set bk_value = bk_value + 1 where bk_name = 'Qty Entries';
  end;

create trigger log_entries_count_delete_trigger after delete on log_entries
  for each row
  begin
    update bookkeepings set bk_value = bk_value - 1 where bk_name = 'Qty Entries';
  end;

您可以将limit 1更改为limit 100以删除100行。