mssql 刪除資料庫中所有的表,mssql刪除資料庫

來源:互聯網
上載者:User

mssql 刪除資料庫中所有的表,mssql刪除資料庫

<pre name="code" class="html">針對於此操作大家可以去先去瞭解一下系統資料表sysobjects(有上篇部落格有寫) ,和drop ,truncate,delete的區別。
------------刪除所有表的外鍵約束(刪除表結構(drop)的時候,刪除資料(truncate;delete )的時候不用)-------DECLARE c1 cursor forselect 'alter table ['+ object_name(parent_obj) + '] drop constraint ['+name+']; 'from sysobjectswhere xtype = 'F'open c1--建立遊標declare @c1 varchar(8000)fetch next from c1 into @c1while(@@fetch_status=0)beginexec(@c1)fetch next from c1 into @c1endclose c1deallocate c1 --------------------刪除所有表-------------------------- use 資料庫名GOdeclare @sql varchar(8000)while (select count(*) from sysobjects where type='U')>0beginSELECT @sql='drop table ' + nameFROM sysobjectsWHERE (type = 'U')ORDER BY 'drop table ' + nameexec(@sql)end


<pre name="code" class="html">    1. truncate 和 delete 只刪除資料不刪除表的結構(定義)    drop 語句將刪除表的結構被依賴的約束(constrain)、觸發器(trigger)、索引(index);依賴於該表的預存程序/函數將保留,但是變為 invalid (無效)狀態。       2. truncate 刪除所有記錄,重設表(最明顯的是自動id歸零),刪除資料時不會備份;delete 刪除記錄,自動id繼續delect刪除時會有備份 是一個DDL語言,向其他所有的DDL語言一樣,他將被隱式提交,不能對 truncate 使用ROLLBACK命令。     3.小心使用 drop 和 truncate,用delete並且帶上where條件,當然客戶那大多都會有備份三者其實沒有優先順序,適當的時候用適當的方法   # 想刪除部分資料行用 delete,注意帶上where子句.  # 想刪除表,當然用 drop      # 想保留表而將所有資料刪除,如果和事務無關,用truncate即可。如果和事務有關,或者想觸發trigger,還是用delete。      # 如果是整理表內部的片段,可以用truncate跟上reuse stroage,再重新匯入/插入資料。



相關文章

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.