般建議盡可能使用delete去刪除表的字段,它具有選擇性刪除的作用,所以常常delete from tablename where 條件 delete和truncate作用其實是一樣的,隻是truncate后面不跟where條件句,它的作用是刪除表中所有的行(記錄) 兩者最大的區別就是delete是寫日誌文件的,而truncate則不寫日誌直接刪除,前者可恢復,而后者無法恢復,后者的危險性更高,所以一般不建議使用truncate,常用delete
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