Tuesday, September 6, 2011

MS SQL Server Drop all tables quickly


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 start here]
select name into #tables from sys.objects where type = ‘U’
while (select count(1) from #tables) > 0
begin
declare @sql varchar(max)
declare @tbl varchar(255)
select top 1 @tbl = name from #tables
set @sql = ‘drop table ‘ + @tbl
exec(@sql)
delete from #tables where name = @tbl
end
drop table #tables;
[/sql end here]

No comments: