如何使用 T-SQL 临时禁用外键约束?

2023-07-17数据库问题
3

本文介绍了如何使用 T-SQL 临时禁用外键约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 SQL Server 中是否支持禁用和启用外键约束?或者是我删除然后重新创建约束的唯一选择?

Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re-create the constraints?

推荐答案

如果您想禁用数据库中的所有约束,只需运行以下代码:

If you want to disable all constraints in the database just run this code:

-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

要重新打开它们,请运行:(打印当然是可选的,它只是列出表格)

To switch them back on, run: (the print is optional of course and it is just listing the tables)

-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

我发现将数据从一个数据库填充到另一个数据库时很有用.这是比删除约束更好的方法.正如您所提到的,在删除数据库中的所有数据并重新填充它时(例如在测试环境中),它会派上用场.

I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

如果您要删除所有数据,您可能会发现 这个解决方案很有帮助.

If you are deleting all the data you may find this solution to be helpful.

有时禁用所有触发器也很方便,您可以查看完整的解决方案 此处.

Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.

这篇关于如何使用 T-SQL 临时禁用外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12

为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)...
2024-04-16 数据库问题
13