码迷,mamicode.com
首页 > 数据库 > 详细

使用SQL语句清空数据库所有表的数据

时间:2019-10-14 10:34:59      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:har   字符串   set   arch   name   char   status   存储过程   type   

利用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‘
exec (@trun_name)
该方法适合表不是非常多的情况,否则表数量过多,超过字符串的长度,不能进行完全清理.
2.利用游标清理所有表


 declare @trun_name varchar(50)
declare name_cursor cursor for
select ‘truncate table ‘ + name from sysobjects where xtype=‘U‘
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 ?"

使用SQL语句清空数据库所有表的数据

标签:har   字符串   set   arch   name   char   status   存储过程   type   

原文地址:https://www.cnblogs.com/linjincheng/p/11669778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!