我想创建一个与此类似的SQLite trigger:
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
将失败并且根本不会发起任何记录。是否可以通过触发器执行此操作?
我阅读了文档,但除了没有完全理解RAISE
之外,我没有找到实现这一目标的方法。
PS :我知道我可以采取其他几种方法来获取唯一的电子邮件列表,但这不是这个问题的重点。如果我可以在触发器内执行此检查/中止,那么这将简化事情。
答案 0 :(得分:2)
Found答案:
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;