The most dangerous SQL Script in the world!
- by DrJohn
In my last blog entry, I outlined how to automate SQL Server database builds from concatenated SQL Scripts. However, I did not mention how I ensure the database is clean before I rebuild it. Clearly a simple DROP/CREATE DATABASE command would suffice; but you may not have permission to execute such commands, especially in a corporate environment controlled by a centralised DBA team. However, you should at least have database owner permissions on the development database so you can actually do your job! Then you can employ my universal "drop all" script which will clear down your database before you run your SQL Scripts to rebuild all the database objects.
Why start with a clean database?
During the development process, it is all too easy to leave old objects hanging around in the database which can have unforeseen consequences. For example, when you rename a table you may forget to delete the old table and change all the related views to use the new table. Clearly this will mean an end-user querying the views will get the wrong data and your reputation will take a nose dive as a result!
Starting with a clean, empty database and then building all your database objects using SQL Scripts using the technique outlined in my previous blog means you know exactly what you have in your database. The database can then be repopulated using SSIS and bingo; you have a data mart "to go".
My universal "drop all" SQL Script
To ensure you start with a clean database run my universal "drop all" script which you can download from here: 100_drop_all.zip
By using the database catalog views, the script finds and drops all of the following database objects:
Foreign key relationships
Stored procedures
Triggers
Database triggers
Views
Tables
Functions
Partition schemes
Partition functions
XML Schema Collections
Schemas
Types
Service broker services
Service broker queues
Service broker contracts
Service broker message types
SQLCLR assemblies
There are two optional sections to the script: drop users and drop roles. You may use these at your peril, particularly as you may well remove your own permissions!
Note that the script has a verbose mode which displays the SQL commands it is executing. This can be switched on by setting @debug=1.
Running this script against one of the system databases is certainly not recommended! So I advise you to keep a USE database statement at the top of the file.
Good luck and be careful!!