返回    建站常识 > 正文

清空数据库中所有表记录 记录ID恢复从0开始

浏览次数:730次 添加时间:2010-10-14

在网站建设中,笔者经常遇到个问题,在用原网站做测试数据时,会有很多的临时数据,不断地积累,到后来,没有一个数据,id已经从几万开始了,看了很不爽,决定把这些表的ID从新置0,从是表比较多,如果一张一张的清空,实在麻烦,因此就想利用SQL语句一次清空所有数据.找到了三种方法进行清空.使用的数据库为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 ?"
 

该方法可以一次清空所有表,但不能加过滤条件.

 

手机地图   一键拨号:400-881-0901
@2013 南京逗点有限公司 www.nanjingweb.com