执行 SQLite 更改表技巧时更新外键引用

发布于 2024-10-16 04:07:40 字数 448 浏览 9 评论 0原文

在 SQLite FAQ[1] 中提到 SQLite 没有完整的 ALTER TABLE 支持。在 StackOverflow [2] 的上一个问题中,提到了完成表修改的技巧。

我想知道的是如何保留外键引用,因为这些引用被移动到随后被删除的重命名表。我是否应该对与我正在修改的实际表有外键关系的每个表执行相同的技巧?

[1] http://www.sqlite.org/lang_altertable.html

[2] 如何重命名 SQLite 数据库表中的列?

In the SQLite FAQ[1] it is mentioned that SQLite does not have full ALTER TABLE support. In a previous question on StackOverflow [2] a trick is mentioned to accomplish table modifications.

What I would like to know is how to keep FOREIGN KEY references as these are moved to the renamed table which is subsequently deleted. Should I do the same trick with each and every table that has a foreign key relationship with the actual table I am modifying?

[1] http://www.sqlite.org/lang_altertable.html

[2] How do I rename a column in a SQLite database table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

宛菡 2024-10-23 04:07:40

是的,你需要做同样的“技巧”。当您重命名引用的表时,外键约束仍然以其新名称引用它。由于 SQLite 不支持“DROP CONSTRAINT”,因此您还必须使用更正的外键约束重建引用表。

事实上,在更正外键引用之前,您将无法删除旧表。只要PRAGMAforeign_keys=ON;,SQLite3就不会让你删除仍然有外键引用它的表。

Yes, you'll need to do the same "trick". When you rename the referenced table, foreign key constraints still refer to it under its new name. Since SQLite doesn't support "DROP CONSTRAINT", you'll have to rebuild the referencing tables with the corrected foreign key constraints, too.

In fact, you won't be able to drop the old table until you correct the foreign key references. As long as PRAGMA foreign_keys=ON;, SQLite3 won't let you drop a table that still has foreign keys referencing it.

吻风 2024-10-23 04:07:40

对于当前版本的 SQLite,当使用 PRAGMAforeign_keys=OFF 禁用外键处理时,不会重写其他表中的引用约束。

不能说这种行为在 2011 年是否有所不同。

With current versions of SQLite referencing constraints in other tables are not rewritten when foreign key handling has been disabled using PRAGMA foreign_keys=OFF.

Can't say if that behavior was different in 2011.

哭了丶谁疼 2024-10-23 04:07:40

对我有帮助的技巧:

alter table some RENAME to some_old;
CREATE TABLE IF NOT EXISTS some (.....)
insert into some select * from some_old;
DROP TABLE IF EXISTS some_old;
alter table some RENAME to some_old;
alter table some_old rename to some;

在此序列之后,外键指向 some 而不是 some_old

The trick that helped me:

alter table some RENAME to some_old;
CREATE TABLE IF NOT EXISTS some (.....)
insert into some select * from some_old;
DROP TABLE IF EXISTS some_old;
alter table some RENAME to some_old;
alter table some_old rename to some;

After this sequence foreign keys are pointing to some and not to some_old

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文