sql中批量删除带有外键的所有表

1首先删除所有的外检约束

--删除所有外键约束

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

2删除所有的表

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

以前在oracle中经常遇到没法删掉数据库的问题(因为一个用户对应一个数据库),所以必须要删除表(要先删除外检约束),在重新生成, 今天在sql试了试,

成功了。

上一篇:MySQL 如何删除有外键约束的表数据


下一篇:MySQL的数据类型,MySQL增删改--添加主外键、添加属性、删除主外键、改表名、获取系统当前时间等