Script(s)

what I learn is what u c

SQL Server, Clean your Database Records and reset Identity Columns, The Shortest Path

with 4 comments

(Copied from Moses’s Blog for my reference)

Well, I had a small issue regarding writing a script to clean a database we have and reset its identity columns in all tables. Although the database wasn’t huge one (less than 100 tables) I had to trace relations to be able to delete child table’s records before parent’s ones because of the foreign key constraints. The solution is disable the foreign keys and delete records with no fear of any errors then enables the constraints again.
Well, I found a solution to disable all constraints without the need to go on each table and disable it manually. and I was happy to know that I can use this solution in deleting all records from all tables. Not only this I was able to use the same solution to reset identity columns in all tables.

The solution was to use this built in stored procedure sp_MSforeachtable. For help about this proc search for it in Books online or use this sp_helptext sp_MSForeachtable.

Now back to my 6 lines, bellow is how I re-zeroed my Database:


1: /*Disable Constraints & Triggers*/
2: exec sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
3: exec sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'
4:
5: /*Perform delete operation on all table for cleanup*/
6: exec sp_MSforeachtable 'DELETE ?'
7:    
8: /*Enable Constraints & Triggers again*/
9: exec sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
10: exec sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'
11:   
12: /*Reset Identity on tables with identity column*/
13: exec sp_MSforeachtable 'IF OBJECTPROPERTY(OBJECT_ID(''?''), ''TableHasIdentity'') = 1 BEGIN DBCC CHECKIDENT (''?'',RESEED,0) END'

Advertisement

Written by gchandra

February 18, 2008 at 10:23 am

4 Responses

Subscribe to comments with RSS.

  1. Thank you for your SQL script…

    Ken

    October 5, 2008 at 11:08 pm

  2. Thanks for the gr8 script… I really like it…

    Ashok Samson

    November 18, 2008 at 8:30 am

  3. wow..Mr. really it is very useful. u saved my head ache..
    thanks.

    muthu

    August 13, 2009 at 1:20 am

  4. Many Thanks it works 100 % for me even my data base is on sql server 2012 and have many tables with constraints and many relations , you are so smart 🙂

    Brahim Atia

    June 9, 2012 at 3:36 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: