Database Journal
MS SQL Oracle DB2 Access MySQL PostgreSQL Sybase PHP SQL Etc SQL Scripts & Samples Tips Database Forum

» Database Journal Home
» Database Articles
» Database Tutorials
MS Access
SQL Scripts & Samples
» Database Forum
» Slideshows
» Sitemap
Free Newsletters:

By submitting your information, you agree that databasejournal.com may send you databasejournal offers via email, phone and text message, as well as email offers about other products and services that databasejournal believes may be of interest to you. databasejournal will process your information in accordance with the Quinstreet Privacy Policy.

News Via RSS Feed

Database Journal |DBA Support |SQLCourse |SQLCourse2

Featured Database Articles

SQL Scripts & Samples

Posted Jul 29, 2002

Disabling or Enabling All Constraints of a Table or Database

By Eli Leiba

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 
              @TblName   VARCHAR(128),
           @State BIT = 1
IF @State = 0
             SET @SQLState = 'ALTER TABLE '+ @TblName + ' NOCHECK CONSTRAINT ALL'
                    SET @SQLState = 'ALTER TABLE ' + @TblName + ' CHECK CONSTRAINT ALL'
EXEC (@SQLState)

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

EXEC sp_disable_all_const_in_db

» See All Articles by Columnist Eli Leiba

SQL Scripts & Samples Archives

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Latest Forum Threads
SQL Scripts & Samples Forum
Topic By Replies Updated
sql help!! add 1 August 22nd, 11:58 AM
How To Combine These 2 Queries into 1 Query ? tarek_land 1 June 7th, 08:37 AM
solving query svibuk 1 February 3rd, 06:08 AM
converting from a character string to uniqueidentifier saturnius 4 January 4th, 05:56 AM