清除表資料一般有兩種方法:
1.truncate table tablename
2.delete from tablename
兩者最大的差別就是delete使寫日志檔案的,而truncate不寫日志直接删除,前者可恢複,而後者無法恢複,後者的危險性更高,是以一般不建議用truncate;
如果要利用SQL語句一次清空所有資料.可以有三種方法:
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 ?"