Search code examples
sqlselectsql-deleteinformation-schema

How to clear all tables selected through a INFORMATION_SCHEMA.TABLES query in SQL?


The result is a list of a few hundred tables that have useless rows that should be cleared. How can I do so without manually typing each one?

Not trying to delete all tables, just the ones that been selected through WHERE AND


Solution

  • DECLARE @SQL_String NVARCHAR(MAX)
    DECLARE @TableName  NVARCHAR(MAX)
    
    DECLARE db_cursor CURSOR FOR
        -- You might want to modify this in order to get only 
        -- a specific subset of tables
        SELECT TABLE_NAME 
        FROM INFORMATION_SCHEMA.TABLES
    OPEN db_cursor   
    
    FETCH NEXT FROM db_cursor 
    INTO @TableName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN 
    
        SET @SQL_String = N'DELETE * FROM ' + QUOTENAME(@TableName)
        EXEC sp_executesql @SQL_STRING
    
        FETCH NEXT FROM db_cursor 
        INTO @TableName        
    END   
    
    CLOSE db_cursor   
    DEALLOCATE db_cursor
    

    Something like this should do the trick.

    As always, when deleting records in tables without a WHERE clause, be very careful.