Thursday, May 14, 2015

Delete Selected list of tables from the SQL database


I have selected tables list which I need to delete from my database. If 10 or less I can do it manually in different ways.
But it has more than 1000 tables which required to delete from the database.

Of course people has their own choice to do this. I have implemented the following script.

First you have to send that list of table names into a temp table.
You may give the Serial number for each row..You can done this by adding extra column with identity property (OR) use
Row_Number() function on the existed column.

Once you are ready with a table with the list of table names(I named it AA_DeletedTables) You can follow the script below.

   
DECLARE @TableName VARCHAR(50)
DECLARE @SQL VARCHAR(100)
DECLARE @i INT =1
DECLARE @Count INT
SELECT @Count = COUNT(*) FROM AA_DeleatedTables

WHILE (@i < =  @Count)
    BEGIN
        SELECT @TableName = name from AA_DeleatedTables WHERE Sno = @i
        SET @SQL = 'Drop table '+@TableName
        --PRINT (@SQL)  You can test by enabling this by just printing the test
        EXEC @SQL
       
        SET @i = @i +1
    END

--SELECT * FROM AA_DeleatedTables

Drop table AA_DeleatedTables
NOTE: It will work for when the tables doesn't have any constraints referencing..
If you want you can use this table as audit table by adding time stamp columns....