Skip to content

如何清空(Truncate)带外键(FK)的表?

🏷️ SQL

使用 TRUNCATE 清空 TABLE 时报如下错误:

无法截断表 'TABLE_NAME',因为该表正由 FOREIGN KEY 约束引用。

SQL Server 对策

案 1

  1. 删除数据;
  2. 重置自增的种子序列(如果有自增字段的话);
sql
DELETE FROM [TABLE_NAME]
DBCC CHECKIDENT ('TABLE_NAME', RESEED, 0)

案 2

  1. 删除外键约束;
  2. 执行 TRUNCATE
  3. 增加外键约束;
sql
BEGIN TRAN
ALTER TABLE [TABLE_NAME] DROP CONSTRAINT [FK_KEY_NAME]
TRUNCATE TABLE [TABLE_NAME]
ALTER TABLE [TABLE_NAME]  WITH NOCHECK ADD CONSTRAINT [FK_KEY_NAME] FOREIGN KEY([COLUMN_NAME]) REFERENCES [ANOTHER_TABLE_NAME] ([COLUMN_NAME])
COMMIT

MySQL 对策

案 1

  1. 禁用外键检查;
  2. 执行 TRUNCATE
  3. 恢复外键检查;
sql
SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE_NAME;
TRUNCATE ANOTHER_TABLE_NAME;

SET FOREIGN_KEY_CHECKS = 1;

案 2

  1. 删除数据;
  2. 重置自增的种子序列(如果有自增字段的话);
sql
DELETE FROM TABLE_NAME;
ALTER TABLE TABLE_NAME AUTO_INCREMENT = 1;

案 3

  1. 删除外键约束;
  2. 执行 TRUNCATE
  3. 增加外键约束;
sql
START TRANSACTION;
ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign Key Name>;
TRUNCATE <Table Name>;
TRUNCATE <Another Table Name>;
ALTER TABLE <Table Name> ADD CONSTRAINT <Foreign Key Name> FOREIGN KEY <Foreign Key Name>(<Field Name>) REFERENCES <Another Table Name>(<Field Name>);
COMMIT;

参考

  1. Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?
  2. How to truncate a foreign key constrained table?
  3. Alter table to add the foreign