Skip to content

sql清除数据库中所有的表

web240 edited this page Nov 30, 2016 · 3 revisions

##清空表 ###方法一 使用sql删除数据库中所有表是不难的,就是遍历一下数据库中所有用户表,并将它清除,下边是具体的sql语句,在关键部分已经作了详细的注释:

--变量@tablename保存表名
declare @tablename nvarchar(100)
--将用户表全部保存到临时表#tablename中
SELECT [name] into #tablename FROM sysobjects
WHERE type = 'U';
--当#tablename有数据时
while(select count(1) from #tablename)>0
begin
--从#tablename中取第一条
select top 1 @tablename=[name] from #tablename;
--进行表删除操作,表名为变量,所以此处用到动态sql
exec('drop table '+@tablename);
--将此表名记录从#tablename中删除
delete from #tablename where [name]=@tablename;
end
--最后删除临时表#tablename
drop table #tablename

可见sql里没有使用游标,而是使用了临时表用来遍历,到这里就达到了使用sql清除数据库中所有表的目的。 ###方法二 方便删除数据库中所有的数据表,清空数据库,有些有约束,不能直接delete,需要先删除库中的约束,代码如下

--删除所有约束 
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 nextfrom c1 into@c1 
while(@@fetch_status=0) 
begin 
exec(@c1) 
fetch nextfrom c1 into@c1 
end 
close c1 
deallocate c1 
--删除数据库所有表 
declare @tname varchar(8000) 
set@tname='' 
select@tname=@tname+Name+','from sysobjects where xtype='U' 
select@tname='drop table '+ left(@tname,len(@tname)-1) 
exec(@tname)

然后清空数据库中的所有表

如果需要删除存储过程等只需要将上面的做如下修改就行了的where xtype='U' 改成 where xtype='P',drop table 改成 drop Procedure

##清空数据表中所有数据

清空所有数据.找到了三种方法进行清空.使用的数据库为MS SQL SERVER. ###1.搜索出所有表名,构造为一条SQL语句

declare @trun_name varchar(8000)
set @trun_name=''
select @trun_name=@trun_name + 'truncate table ' + [name] + ' ' from sysobjects where xtype='U' and status > 0
exec (@trun_name)

该方法适合表不是非常多的情况,否则表数量过多,超过字符串的长度,不能进行完全清理. ###2.利用游标清理所有表

declare @trun_name varchar(50)
declare name_cursor cursor for
select 'truncate table ' + name from sysobjects where xtype='U' and status > 0
open name_cursor
fetch next from name_cursor into @trun_name
while @@FETCH_STATUS = 0
begin
  exec (@trun_name)
 print 'truncated table ' + @trun_name
 fetch next from name_cursor into @trun_name
end
close name_cursor
deallocate name_cursor

这是我自己构造的,可以做为存储过程调用, 能够一次清空所有表的数据,并且还可以进行有选择的清空表. ###3.利用微软未公开的存储过程

exec sp_msforeachtable "truncate table ?"
Clone this wiki locally