博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

清空DB

Posted on 2011-01-14 16:36  moss_tan_jun  阅读(523)  评论(0编辑  收藏  举报
清除表数据一般有两种方法:
1.truncate table tablename
2.delete from tablename
两者最大的区别就是delete使写日志文件的,而truncate不写日志直接删除,前者可恢复,而后者无法恢复,后者的危险性更高,所以一般不建议用truncate;
如果要利用SQL语句一次清空所有数据.可以有三种方法:
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 ?"