Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?(无法截断表,因为它被 FOREIGN KEY 约束引用?)
问题描述
使用MSSQL2005,如果先截断子表(外键关系的主键的表),是否可以截断带外键约束的表?
Using MSSQL2005, can I truncate a table with a foreign key constraint if I first truncate the child table (the table with the primary key of the FK relationship)?
我知道我也可以
- 使用不带 where 子句的
DELETE
,然后RESEED
标识(或) - 删除 FK,截断表格,然后重新创建 FK.
我认为只要我在父表之前截断子表,我就可以不执行上述任何一个选项,但是我收到了这个错误:
I thought that as long as I truncated the child table before the parent, I'd be okay without doing either of the options above, but I'm getting this error:
无法截断表TableName",因为它被 FOREIGN KEY 约束引用.
Cannot truncate table 'TableName' because it is being referenced by a FOREIGN KEY constraint.
推荐答案
正确;您不能截断具有 FK 约束的表.
Correct; you cannot truncate a table which has an FK constraint on it.
通常我的流程是:
- 放弃约束
- 整理表格
- 重新创建约束.
(当然,一切都在交易中.)
(All in a transaction, of course.)
当然,这只适用于 子节点已经被截断的情况. 否则我会走不同的路线,完全取决于我的数据是什么样的.(这里的变量太多了.)
Of course, this only applies if the child has already been truncated. Otherwise I go a different route, dependent entirely on what my data looks like. (Too many variables to get into here.)
原发帖人确定了为什么会这样;请参阅 这个答案 了解更多详情.
The original poster determined WHY this is the case; see this answer for more details.
这篇关于无法截断表,因为它被 FOREIGN KEY 约束引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法截断表,因为它被 FOREIGN KEY 约束引用?


- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01