SQL Serve清空所有表的数据

浏览: 2649

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 ?"


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


推荐 2
本文由 梁勇 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册