34,876
社区成员
发帖
与我相关
我的任务
分享
8楼的方法 最接近,但是有2个问题
1.就是你的 ‘like 'temptb_%';’ 中下划线_没有转义字符,如果有一个‘temptb789’的表,你一样能删除
2.就是你的 sys.tables 中如果有系统表,他也一样要删除,例如‘数据库中系统表中有个dbo.dtproperties’的,修改就是加上一个判断 is_ms_shipped =0,这样就是指的用户表。
借鉴8楼修改如下:
-- 测试数据
create table dbo.temptb_1 (id int);
create table guest.temptb_2 (id int);
-- 打开隐式事务
SET IMPLICIT_TRANSACTIONS ON
-- 执行动态删除
declare @sql varchar(max);
set @sql='';
select @sql=@sql+'drop table '+
QUOTENAME(SCHEMA_NAME([schema_id]))+'.'+QUOTENAME([name])+';'
from sys.tables where where is_ms_shipped =0 and [name] like 'temptb\_%' escape '\'
--select @sql;
EXEC(@sql);
-- 检查删除是否正确
select * from sys.tables
-- 正确,则提交事务,确认删除
commit tran
-- 不正确,则回滚事务,取消删除
rollback tran
-- 关闭隐式事务
SET IMPLICIT_TRANSACTIONS OFF
-- 测试数据
create table dbo.temptb_1 (id int);
create table guest.temptb_2 (id int);
-- 打开隐式事务
SET IMPLICIT_TRANSACTIONS ON
-- 执行动态删除
declare @sql varchar(max);
set @sql='';
select @sql=@sql+'drop table '+
QUOTENAME(SCHEMA_NAME([schema_id]))+'.'+QUOTENAME([name])+';'
from sys.tables where [name] like 'temptb_%';
--select @sql;
EXEC(@sql);
-- 检查删除是否正确
select * from sys.tables
-- 正确,则提交事务,确认删除
commit tran
-- 不正确,则回滚事务,取消删除
rollback tran
-- 关闭隐式事务
SET IMPLICIT_TRANSACTIONS OFF
select * from sys.tables where is_ms_shipped =0 and name like 'temptb\_%' escape '\'
exec sp_msforeachtable 'drop table ?',@whereand=' and name like ''temptb_%'''SQL批量删除用户表(先删除所有外键约束,再删除所有表)
--删除外键约束
DECLARE c1 cursor for
select 'alter table ['+ object_name(parent_obj) + '] drop constraint ['+name+']; '
from sysobjects
where xtype = 'F' and object_name(parent_obj) like 'temptb_%'
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
--删除表
DECLARE c2 cursor for
select 'drop table ['+name +']; '
from sysobjects
where xtype = 'u' and name like 'temptb_%'
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
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/htl258/archive/2009/07/16/4352355.aspxdeclare @s varchar(1000)
set @s=''
select @s=@s+' drop table '+name+';' from sysobjects where type='U' and name like'temptb%'
exec( @s)declare @sql varchar(8000)
set @sql=''
select @sql=@sql+' drop table ['+name+'] ' from sysobjects where xtype='u' and name like 'temptb_%'
exec(@sql)
--drop table
exec sp_msforeachtable 'if ''?'' like ''/[dbo/]./[temptb_%'' escape ''/'' drop table ? '
--delete
exec sp_msforeachtable 'if ''?'' like ''/[dbo/]./[temptb_%'' escape ''/'' delete ? '