SQL 清空數據庫的所有表數據

 近來發現數據庫過大,空間不足,因此打算將數據庫的數據進行全面的清理,但表非常多,一張一張的清空,實在麻煩,因此就想利用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 ?"

該方法可以一次清空所有表,但不能加過濾條件.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章