我想创建一个类似于此的SQLite触发器:
CREATE TRIGGER "prevent_duplicate_emails" BEFORE INSERT OF "email" ON "users" FOR EACH ROW BEGIN SELECT COUNT("email") FROM "users" WHERE "email" LIKE NEW."email" # FIX ME! IF COUNT("email") > 0: RAISE ABORT|FAIL, NEW."email" || ' already exists' ELSE: INSERT INTO "unique_emails" VALUES (NEW."email"); ENDIF; END;
所以基本上当我这样做时:
INSERT INTO "users" ("email") VALUES ("adam@eden.com"); # WORKS INSERT INTO "users" ("email") VALUES ("adam@eden.com"); # FAILS INSERT INTO "users" ("email") VALUES ("eve@eden.com"); # WORKS
第一个INSERT将产生两个新记录(在表users和中unique_emails),而第二个INSERT将失败并且根本不产生任何记录。是否可以通过触发器执行此操作?
INSERT
users
unique_emails
我阅读了文档,但是除了没有完全理解之外,RAISE我没有看到实现此目的的方法。
RAISE
PS :我知道我可以采取其他几种方法来获取唯一的电子邮件列表,但这不是这个问题的重点。如果我可以在触发器内执行此检查/中止操作,那真的可以简化事情。
找到了答案:
CREATE TRIGGER IF NOT EXISTS "prevent_duplicate_emails" BEFORE INSERT OF "email" ON "users" FOR EACH ROW BEGIN SELECT RAISE(ABORT, 'Email already exists.') WHERE EXISTS (SELECT 1 FROM "unique_emails" WHERE "email" LIKE NEW."email"); INSERT INTO "unique_emails" VALUES (NEW."email"); END;