1. 程式人生 > >刪除指定資料庫所有表

刪除指定資料庫所有表

無主外來鍵關係的表
use sq_mstfr715164
GO
declare @sql varchar(8000)
while (select count(*) from sysobjects where type='U')>0
begin
SELECT @sql='drop table ' + name
FROM sysobjects
WHERE (type = 'U')
ORDER BY 'drop table ' + name
exec(@sql) 
end

如果有主外來鍵關係的,需先刪除主外來鍵,再刪除所有表

use sq_mstfr715164
DECLARE c1 cursor for
select 'alter table ['+ object_name(parent_obj) + '] drop constraint ['+name+']; '
from sysobjects
where xtype = 'F'
open c1
declare @c1 varchar(8000)
fetch next from c1 into @c1
while(@@fetch_status=0)
begin
exec(@c1)
fetch next from c1 into @c1
end
close c1
deallocate c1

--再來刪除表,會刪除該資料庫(例test)下所有表

DECLARE c2 cursor for
select 'drop table ['+name +']; '
from sysobjects
where xtype = 'u'
open c2
declare @c2 varchar(8000)
fetch next from c2 into @c2
while(@@fetch_status=0)
begin
exec(@c2)
fetch next from c2 into @c2
end
close c2
deallocate c2