SQL Server, Drop All Tables in Database Quickly

Posted in: SQL |

Just a quick and dirty way of dropping all the tables in a database, without dropping the database itself.  Useful for when your writing data migration scripts and staging data and need to wipe out your development environment real quick ... or, when you've found that uber cool sql-injection-able site and want to wreak some havoc (I don't condone the latter, but I do think its funny from time to time when it happens to the 'big companies').

SQL:
  1. SELECT name INTO #tables from sys.objects where type = 'U'
  2. while (SELECT count(1) FROM #tables) > 0
  3. begin
  4. declare @sql varchar(max)
  5. declare @tbl varchar(255)
  6. SELECT top 1 @tbl = name FROM #tables
  7. SET @sql = 'drop table ' + @tbl
  8. exec(@sql)
  9. DELETE FROM #tables where name = @tbl
  10. end
  11. DROP TABLE #tables;

Want to Advertise on this Site?