How to Find All Constraint Violations in a SQL Server Database

You can run the DBCC CHECKCONSTRAINTS console command to return a list of all constraint violations in a SQL Server database.

This command checks the integrity of a specified constraint or all constraints on a specified table in the current database. It returns any foreign key and CHECK constraint violations that it finds.

You can use the ALL_CONSTRAINTS option to check both enabled and disabled constraints. If you omit this, then only enabled constraints are returned (unless you explicitly specify a constraint to check, in which case it will be returned regardless of whether it’s enabled or disabled).

Continue reading

How to Disable a Foreign Key Constraint in SQL Server (T-SQL Examples)

If you find yourself in the situation where you need to disable a foreign key constraint in SQL Server, here’s how to do that using Transact-SQL.

This will allow you to enter data without being restricted by the foreign key. Obviously, you wouldn’t do this unless you had a very good reason to do so. Foreign keys enforce referential integrity, so disabling them has the potential to create all sorts of issues.

Continue reading

How to Disable All CHECK & Foreign Key Constraints in a Database in SQL Server (T-SQL Examples)

You can use the code below to disable all CHECK and foreign key constraints for the current database in SQL Server.

EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"

This uses Microsoft’s undocumented sp_MSforeachtable stored procedure. This procedure allows you to perform tasks against each table in a database. So it’s perfect for our task here – to disable all CHECK constraints within the current database.

Below is an example where I do this and then check the result.

Continue reading

How to Enable All CHECK & Foreign Key Constraints in a Database in SQL Server (T-SQL Examples)

You can use the code below to enable all CHECK and foreign key constraints for the current database in SQL Server.

When you enable a CHECK or foreign key constraint, you have the option of checking existing data in the table before the constraint is enabled. Doing this allows you to verify whether or not any existing violates the constraint. To perform this check, use WITH CHECK within the code, otherwise use WITH NOCHECK.

Continue reading

How to Enable All CHECK & Foreign Key Constraints for a Table in SQL Server (T-SQL Examples)

You can use the code below to enable all CHECK and foreign key constraints for a specific table in SQL Server.

When you enable a constraint in SQL Server, you need to decide whether it should check any existing data or not. This is an important consideration if the table already contains data, because that existing data may potentially violate the constraint’s rules.

Continue reading