在SQLite触发器中测试COUNT()> X.

时间:2013-09-11 08:57:30

标签: sql sqlite triggers

如何比较SQLite中触发器内COUNT的结果?

到目前为止,这是我提出的代码:

CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
BEGIN
    SELECT CASE WHEN 
        SELECT COUNT (*) FROM mytable >= 3
    THEN
        RAISE(FAIL, "Activated - mytrigger.")
    END;
END;

无法编译:

Error: near "SELECT": syntax error

如果我用SELECT COUNT (*) FROM mytable >= 3替换1 == 1,它编译得很好,并且触发器始终执行。

3 个答案:

答案 0 :(得分:2)

您需要在整个SELECT语句SELECT COUNT (*) FROM mytable

周围添加括号
CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
BEGIN
    SELECT CASE WHEN 
        (SELECT COUNT (*) FROM mytable) >= 3
    THEN
        RAISE(FAIL, "Activated - mytrigger.")
    END;
END;

答案 1 :(得分:2)

当count大于100时,尝试使用此代码删除table2中的最后50行

CREATE **TRIGGER IF NOT EXISTS** delete_trigger
BEFORE INSERT ON table1 
  WHEN (SELECT COUNT(*) FROM table1) > 100
    BEGIN 
      delete From table1 where id not in (select id from table1 order by id desc limit 50; 
END;

答案 2 :(得分:0)

尝试将计数放在括号内:

CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
BEGIN
    SELECT CASE WHEN 
        SELECT (COUNT (*) FROM mytable) >= 3
    THEN
        RAISE(FAIL, "Activated - mytrigger.")
    END;
END;