批量删除Sql Server对象(表,存储过程,触发器)

先在系统表中找到要处理的表名或者是存储过程的名字,在用游标对其进行处理

PS:SqlServer 2000使用的是系统表是sysobjects,类型字段是:xtype; SqlServer 2005以上版本的系统表是Sys.Objects,类型字段是Type

本文中以Sql2005为例,Sql2000版本请自行按照上述说明进行替换


注意  sys.objects 中type的值不同 删除命令是不同的

如删除存储过程用drop PROCEDURE PROCEDURENAME 删除表用 drop table  tablename 删除触发器用Drop Trigger TriggerName

sys.objects.type的值表示的意思如下表:
C:检查约束。 
D:默认的约束 
F:外键约束 
L:日志 
P:存储过程 
PK:主键约束 
RF:复制过滤存储过程 
S:系统表格 
TR:触发器 
U:用于表格。 
UQ:独特的约束。

批量处理的代码如下:
DECLARE cursorname cursor for select 'drop PROCEDURE  '+name from sys.objects where name like 'xx%' and xtype = 'p' --删除对应的存储过程
DECLARE cursorname cursor for select 'drop Trigger'+name from sys.objects where name like 'xx%' and xtype = 'tr' --删除对应的触发器

open cursorname
declare @curname sysname
fetch next from cursorname into @curname
while(@@fetch_status=0)
  begin
 exec(@curname)
fetch next from cursorname into @curname
end
close cursorname
deallocate cursorname 

=====================================================

删除表

declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'u' and [name] LIKE 'ns_%'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
if @procName <> 'DeleteAllProcedures'
exec('drop table ' + @procName)
fetch next from cur into @procName
end
close cur
deallocate cur

删除存储过程

declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p' and [name] LIKE 'ns_%'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
if @procName <> 'DeleteAllProcedures'
exec('drop PROCEDURE ' + @procName)
fetch next from cur into @procName
end
close cur
deallocate cur

原文地址:https://www.cnblogs.com/puream/p/2652437.html