These procedures are very important to use when you need to load a bulk of data that you know is correct but when you do not need the foreign keys and check constraints to interfere while you are loading the data. This is also the case when you want to change key values and don't want the constraints to get in your way. The following procedure will disable/enable all constraints for a given parametric table.
-- PROCEDURE to disable/enable all constraints on a table
CREATE PROCEDURE sp_ConstraintState
@State BIT = 1
DECLARE @SQLState VARCHAR(500)
IF @State = 0
SET @SQLState = 'ALTER TABLE '+ @TblName + ' NOCHECK CONSTRAINT ALL'
SET @SQLState = 'ALTER TABLE ' + @TblName + ' CHECK CONSTRAINT ALL'
-- For example:
exec sp_ConstraintState 'products',0
will disable all constraints on the products table in northwind
-- PROCEDURE to disable/enable all constraints in an entire databse (using sp_constraintState)
Create proc sp_disable_all_const_in_db
'exec sp_MsForEachTable 'sp_ConstraintState ''?'',0
to disbale all constraints in the database
See All Articles by Columnist Eli Leiba