首页>>帮助中心>>香港VPS如何使用SQL语句清空数据库所有表的数据

香港VPS如何使用SQL语句清空数据库所有表的数据

2025/1/6 87次

香港VPS近来发现数据库过大,空间不足,因此打算将数据库的数据进行全面的清理,但表非常多,一张一张的清空,实在麻烦,因此就想利用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 > 0exec (@trun_name)
declare @trun_name varchar(8000)set @trun_name=''select @trun_name=@trun_name + 'truncate table ' + [name] + ' ' from sysobjects where xtype='U' and status > 0exec (@trun_name)
该方法适合表不是非常多的情况,否则表数量过多,超过字符串的长度,不能进行完全清理.2.利用游标清理所有表

declare @trun_name varchar(50)declare name_cursor cursor forselect 'truncate table ' + name from sysobjects where xtype='U' and status > 0open name_cursorfetch next from name_cursor into @trun_namewhile @@FETCH_STATUS = 0begin exec (@trun_name) print 'truncated table ' + @trun_name fetch next from name_cursor into @trun_nameendclose name_cursordeallocate name_cursor这是我自己构造的,可以做为存储过程调用, 能够一次清空所有表的数据,并且还可以进行有选择的清空表.3.利用微软未公开的存储过程exec sp_msforeachtable "truncate table ?"
declare @trun_name varchar(50)declare name_cursor cursor forselect 'truncate table ' + name from sysobjects where xtype='U' and status > 0open name_cursorfetch next from name_cursor into @trun_namewhile @@FETCH_STATUS = 0begin exec (@trun_name) print 'truncated table ' + @trun_name fetch next from name_cursor into @trun_nameendclose name_cursordeallocate name_cursor
这是我自己构造的,可以做为存储过程调用, 能够一次清空所有表的数据,并且还可以进行有选择的清空表.3.利用微软未公开的存储过程
exec sp_msforeachtable "truncate table ?"

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

购买使用一诺网络香港服务器,可以极大降低初创企业、中小企业以及个人开发者等用户群体的整体IT使用成本,无需亲自搭建基础设施、简化了运维和管理的日常工作量,使用户能够更专注于自身的业务发展和创新。香港服务器低至29元/月,购买链接:https://www.enuoidc.com/vps.html?typeid=2