使用SQL語句清空資料庫所有表的資料)

來源:互聯網
上載者:User

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.