使⽤SQL语句清空数据库所有表的数据
近来发现数据库过⼤,空间不⾜,因此打算将数据库的数据进⾏全⾯的清理,但表⾮常多,⼀张⼀张的清空,实在⿇烦,因此就想利⽤SQL语句⼀次清空所有数据.到了三种⽅法进⾏清空.使⽤的数据库为MS SQL SERVER.
1.搜索出所有表名,构造为⼀条SQL语句
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 ?"
该⽅法可以⼀次清空所有表,但不能加过滤条件.