这是我的sql语句集:
char *sql = "BEGIN TRANSACTION;
CREATE TABLE Friends(id varchar UNIQUE);
CREATE TABLE Enemies(id2 varchar ,id3 INTEGER,CONSTRAINT id_econst
FOREIGN KEY(id2) REFERENCES Friends(id) ON DELETE CASCADE);
INSERT INTO Friends VALUES('11');
INSERT INTO Friends VALUES('2');
INSERT INTO Enemies VALUES('11',3);
INSERT INTO Enemies VALUES('3',5);
END TRANSACTION;
PRAGMA foreign_keys = ON;
DELETE FROM Friends WHERE id = '11';";
在Enemies表上执行级联删除,而:
char *sql = "BEGIN TRANSACTION;
CREATE TABLE Friends(id varchar UNIQUE);
CREATE TABLE Enemies(id2 varchar ,id3 INTEGER,CONSTRAINT id_econst
FOREIGN KEY(id2) REFERENCES Friends(id) ON DELETE CASCADE);
INSERT INTO Friends VALUES('11');
INSERT INTO Friends VALUES('2');
INSERT INTO Enemies VALUES('11',3);
INSERT INTO Enemies VALUES('3',5);
PRAGMA foreign_keys = ON;
DELETE FROM Friends WHERE id = '11';
END TRANSACTION;";
正常删除。
为什么会这样?
答案 0 :(得分:1)
您正在事务中启用外键支持。引用sqlite:
此pragma是事务中的无操作
https://sqlite.org/pragma.html#pragma_foreign_keys
在第二个示例中,pragma无效,并且不强制执行外键约束。