2

如何比较 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 >= 31 == 1,它编译得很好,并且触发器总是执行。

4

3 回答 3

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;
于 2013-09-11T09:15:11.893 回答
2

当计数大于 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;
于 2013-09-27T10:31:37.910 回答
0

尝试将计数放在括号内:

CREATE TRIGGER mytrigger
BEFORE INSERT ON mytable
BEGIN
    SELECT CASE WHEN 
        SELECT (COUNT (*) FROM mytable) >= 3
    THEN
        RAISE(FAIL, "Activated - mytrigger.")
    END;
END;
于 2013-09-11T09:17:41.170 回答