无法截断表,因为它被 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.

通常我的流程是:

  1. 放弃约束
  2. 整理表格
  3. 重新创建约束.

(当然,一切都在交易中.)

(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.

相关文章