删除指定数据库所有表

来源:互联网 发布:淘宝网店怎么起步快 编辑:程序博客网 时间:2024/04/29 22:24
无主外键关系的表
use sq_mstfr715164GOdeclare @sql varchar(8000)while (select count(*) from sysobjects where type='U')>0beginSELECT @sql='drop table ' + nameFROM sysobjectsWHERE (type = 'U')ORDER BY 'drop table ' + nameexec(@sql) end


如果有主外键关系的,需先删除主外键,再删除所有表

use sq_mstfr715164DECLARE c1 cursor forselect 'alter table ['+ object_name(parent_obj) + '] drop constraint ['+name+']; 'from sysobjectswhere xtype = 'F'open c1declare @c1 varchar(8000)fetch next from c1 into @c1while(@@fetch_status=0)beginexec(@c1)fetch next from c1 into @c1endclose c1deallocate c1--再来删除表,会删除该数据库(例test)下所有表DECLARE c2 cursor forselect 'drop table ['+name +']; 'from sysobjectswhere xtype = 'u'open c2declare @c2 varchar(8000)fetch next from c2 into @c2while(@@fetch_status=0)beginexec(@c2)fetch next from c2 into @c2endclose c2deallocate c2


0 0