SQL中一次清空數(shù)據(jù)庫(kù)所有數(shù)據(jù)的語(yǔ)句寫(xiě)法
下面將為您介紹SQL中一次清空數(shù)據(jù)庫(kù)所有數(shù)據(jù)的語(yǔ)句寫(xiě)法,供您參考,如果您在使用SQL數(shù)據(jù)庫(kù)時(shí)也遇到了類(lèi)似的問(wèn)題,不妨一看,相信對(duì)您會(huì)有所啟迪.
近來(lái)發(fā)現(xiàn)數(shù)據(jù)庫(kù)過(guò)大,空間不足,因此打算將數(shù)據(jù)庫(kù)的數(shù)據(jù)進(jìn)行全面的清理,但表非常多,一張一張的清空,實(shí)在麻煩,因此就想利用SQL語(yǔ)句一次清空所有數(shù)據(jù).找到了三種方法進(jìn)行清空.使用的數(shù)據(jù)庫(kù)為MS SQL SERVER.
1.搜索出所有表名,構(gòu)造為一條SQL語(yǔ)句
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)
該方法適合表不是非常多的情況,否則表數(shù)量過(guò)多,超過(guò)字符串的長(zhǎng)度,不能進(jìn)行完全清理.
2.利用游標(biāo)清理所有表
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
這是我自己構(gòu)造的,可以做為存儲(chǔ)過(guò)程調(diào)用, 能夠一次清空所有表的數(shù)據(jù),并且還可以進(jìn)行有選擇的清空表.
3.利用微軟未公開(kāi)的存儲(chǔ)過(guò)程
exec sp_msforeachtable "truncate table ?"
該方法可以一次清空所有表,但不能加過(guò)濾條件.
【編輯推薦】