Wednesday, October 24, 2007

Bored? Delete all tables!

Ok, so I had the rare occasion to have to delete all the tables from, rather than just drop, a database. I wanted to preserve the stored procs and diagrams. So, I did this:


set nocount on

declare @tname nvarchar(50), @sqlcmd nvarchar(100)
declare @tables table (table_name nvarchar(50) not null)

insert into @tables
select table_name from information_schema.tables
where table_type = 'BASE TABLE'

while (select count(*) from @tables) > 0
begin
set @tname = (select top 1 table_name from @tables)
set @sqlcmd = 'drop table ' + @tname
print @sqlcmd
delete from @tables where table_name = @tname
end


This doesn't delete all tables, but it does provide you a pre-written script for doing so. Copy, paste, and run.

2 comments:

Unknown said...

If you want to delete all tables in a database, truncate them
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/truncate-all-tables-part-ii.aspx

http://sqlblogcasts.com/blogs/madhivanan

David M Maxwell said...

That's a good way to truncate. I'll make a note of it. (My goal, though, was actually to delete the tables, rather than truncate them.)

Thanks for the tip.

-D.