删除/截断表中具有外键的记录

发布于 2025-01-04 23:57:54 字数 451 浏览 1 评论 0原文

这是我的要求,我试图根据 Adventure 作品数据库来详细说明这一点。

我必须删除具有约束和外键关系的 Production.Product 表的所有记录,并填充其他表中的数据(当前我正在使用此语句复制表中的数据)

SELECT * INTO Product_temp
FROM [AdventureWorks].[Production].[Product]

所以我必须删除 Product 表中的所有记录和然后从 product_temp 插入。

我找到了这个答案,但我无法在 SQL SERVER 2005

SQL Server 2005 级联 中找到此选项删除

This is my requirement, I am trying to elaborate that in terms of Adventure works database.

I have to delete all records of Production.Product table which has constraints and Foreign key relation and fill the data from other table (currently I am using this statement to copy data in the table)

SELECT * INTO Product_temp
FROM [AdventureWorks].[Production].[Product]

So I have to delete all records from Product table and then insert from product_temp.

I have found this answer, but I am unable to find this option in SQL SERVER 2005

SQL Server 2005 Cascading Delete

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

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

发布评论

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

评论(2

孤星 2025-01-11 23:57:54

如果您能够对所有四个表进行批量替换,那么最快的策略是删除所有四个表中的所有行并重新插入,而不是执行“Upsert”(好术语@marc_s)。那里的一个建议是:我建议使用 TRUNCATE 来清除表,而不是 DELETE。这表现得更好,因为引擎避免将所有这些已删除的记录写入事务日志。显然,您需要首先删除“边缘”表,即那些与其他表有 FK 的表。

如果您发现表具有循环引用,使得很难从表中删除行,那么我会这样做:

  1. 从表中删除所有约束
  2. 截断目标表(顺序并不重要,因为约束消失了)
  3. 导入数据(如果可以的话,请使用 bcp 以实现最快加载!)
  4. 重新应用约束
  5. (可选)更新目标表上的统计信息

If you are able to do a wholesale replace of all four tables then your quickest strategy is to delete all rows from all four table and re-insert rather than doing an "Upsert" (good term @marc_s). One recommendation there: I'd recommend using TRUNCATE to clear out your tables rather that DELETE. This performs much better because the engine avoids writing all those deleted records into the transaction log. Obviously you'd need to delete your "fringe" tables first, that ones that have FK's to other tables.

If you find that the tables have circular references that make it hard to delete rows from tables then here's what I'd do:

  1. Drop all constraints from your tables
  2. Truncate your target tables (sequence won't matter since your constraints are gone)
  3. Import the data (use bcp if you can for fastest loading!)
  4. Re-apply constraints
  5. (Optional) Update statistics on the target tables
明媚如初 2025-01-11 23:57:54

您不需要删除外键约束。

  1. 触发删除查询。然后

2.EXEC sp_MSforeachtable 'UPDATE STATISTICS ? AND FULLSCAN'

3.Exec sp_MSforeachtable "dbcc dbreindex('?')"

You don't need to remove the foreign key constraint.

  1. Fire the delete query .Then

2.EXEC sp_MSforeachtable 'UPDATE STATISTICS ? WITH FULLSCAN'

3.Exec sp_MSforeachtable "dbcc dbreindex('?')"

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