Monday 18 February 2013

Drop all tables, stored procedure, views and triggers

Sometimes, there is a case, when we need to remove all tables, stored procedure, views and triggers completely from the database. If you have around 100 tables, stored procedure and views in your database, to remove these, completely from database became a tedious task. In this article, I would like to share the script by which you can remove tables, stored procedure, views and triggers completely from database.

Remove all Tables

  1. -- drop all user defined tables
  2. EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

Remove all User-defined Stored Procedures

  1. -- drop all user defined stored procedures
  2. Declare @procName varchar(500)
  3. Declare cur Cursor For Select [name] From sys.objects where type = 'p'
  4. Open cur
  5. Fetch Next From cur Into @procName
  6. While @@fetch_status = 0
  7. Begin
  8. Exec('drop procedure ' + @procName)
  9. Fetch Next From cur Into @procName
  10. End
  11. Close cur
  12. Deallocate cur

Remove all Views

  1. -- drop all user defined views
  2. Declare @viewName varchar(500)
  3. Declare cur Cursor For Select [name] From sys.objects where type = 'v'
  4. Open cur
  5. Fetch Next From cur Into @viewName
  6. While @@fetch_status = 0
  7. Begin
  8. Exec('drop view ' + @viewName)
  9. Fetch Next From cur Into @viewName
  10. End
  11. Close cur
  12. Deallocate cur

Remove all Triggers

  1. -- drop all user defined triggers
  2. Declare @trgName varchar(500)
  3. Declare cur Cursor For Select [name] From sys.objects where type = 'tr'
  4. Open cur
  5. Fetch Next From cur Into @trgName
  6. While @@fetch_status = 0
  7. Begin
  8. Exec('drop trigger ' + @trgName)
  9. Fetch Next From cur Into @trgName
  10. End
  11. Close cur
  12. Deallocate cur

 

No comments:

Post a Comment