构造为一条SQL语句清空数据库
2010-04-21 16:28
232 查看
近来发现数据库过大,空间不足,因此打算将数据库的数据进行全面的清理,但表非常多,一张一张的清空,实在麻烦,因此就想利用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 ?"
--删除当前数据库所有表中的数据
sp_MSforeachtable @command1='Delete from ?'
sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"
该方法可以一次清空所有表,但不能加过滤条件.
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 ?"
--删除当前数据库所有表中的数据
sp_MSforeachtable @command1='Delete from ?'
sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"
该方法可以一次清空所有表,但不能加过滤条件.
相关文章推荐
- 使用SQL语句清空数据库所有表的数据
- 奇怪!同一条sql语句在数据库和代码中执行结果不同?!当然是人错了 ……
- 一句SQL语句清空当前数据库所有表
- 数据库编程中针对c++的构造sql语句的写法
- 批量替换数据库记录内容的一条SQL语句
- 从数据库中随机抽取一条记录的SQL语句
- 一条SQL语句查询数据库中的所有表、存储过程、触发器 (sysobjects表信息)
- 使用SQL语句清空数据库所有表的数据
- 一条SQL语句查询多个数据库
- 自动生成清空数据库的SQL语句
- 清空数据库所有表,所有存储过程SQL语句
- 通过一条sql语句访问不同数据库服务器中的数据库对象的方法
- Sql 清空数据库表的数据语句
- 通过一条sql语句访问不同数据库服务器中的数据库对象的方法
- 使用SQL语句清空数据库所有表的数据
- 数据库表,3个字段,姓名,薪水,部门,用一条sql语句求每个部门薪水最高的人姓名
- ADO.NET的一个帮助类库,只须一个连接,一条SQL语句,轻松实现数据库的查旬,再加一个object 轻松实现数据库的增删改
- 用一条SQL语句实现向数据库中插入多条记录的方法
- 从数据库中提取新闻的上一条,下一条的sql语句
- C#不同数据库连接方式对应的Sql语句的构造