SQLSERVER删除所有的表、存储过程和视图

--删除所有约束
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
--删除数据库所有表
declare @tname varchar(8000)
set @tname=‘‘
select @+Name+‘,‘from sysobjects where xtype=‘U‘
select @tname=‘drop table ‘+ left(@tname,len(@tname)-1)
exec(@tname)

--删除视图:

declare v_mycur cursor local for select [name] from dbo.sysobjects where xtype=‘V‘  --声明游标
declare @vname varchar(100) 
  
OPEN v_mycur    --打开游标
  
FETCH NEXT from v_mycur into @vname
  
WHILE @@FETCH_STATUS = 0  
  
BEGIN 
exec(‘drop VIEW ‘ + @vname) 
FETCH NEXT from v_mycur into @vname   --逐条读取
END 
  
CLOSE v_mycur   --关闭游标

 

--删除存储过程:



declare mycur cursor local for select [name] from dbo.sysobjects where xtype=‘P‘
declare @name varchar(100) 
  
OPEN mycur 
  
FETCH NEXT from mycur into @name
  
WHILE @@FETCH_STATUS = 0  
  
BEGIN 
exec(‘drop PROCEDURE ‘ + @name) 
FETCH NEXT from mycur into @name
END 
  
CLOSE mycur

相关推荐