Wednesday, December 14, 2011

Clean / Delete all data in Azure database

PROBLEM:
You want to clean / delete all data form all tables in Azure database. You cannot use sp_MSForEachTable to generate delete script

SOLUTION:
Run the following code and save the result as a script, then execute it. You can use this script also in a regular SQL Server
SELECT 'print ''NOCHECK CONSTRAINT ' + f.name + '''; ALTER TABLE ' + '[' + OBJECT_NAME(f.parent_object_id)+ ']'+' NOCHECK CONSTRAINT ' + '[' + f.name + '];'
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
UNION ALL
SELECT 'print ''delete ' + name + '''; DELETE [' + name + '];'
FROM sys.tables
UNION ALL
SELECT 'print ''CHECK CONSTRAINT ' + f.name + '''; ALTER TABLE ' + '[' + OBJECT_NAME(f.parent_object_id)+ ']'+' CHECK CONSTRAINT ' + '[' + f.name + '];'
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id

If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


19 comments:

  1. How can I just make this script execute it as well? I have 200 tables and I cannot run them manually?

    ReplyDelete
  2. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.Your post is just outstanding! thanks for such a post,its really going great and great work.You have provided great knowledge
    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

    ReplyDelete
  3. Addition for schema inclusion, replace select ... sys_tables part with

    SELECT 'print ''delete ' + name + '''; DELETE ['+SCHEMA_NAME(schema_id)+'].['+name+'];'
    FROM sys.tables

    ReplyDelete