Drop a table if it exists then recreate it

I'm trying to do a SQL statement (SQL Server 2012) that looks to see if a database exists and, if it does, drop the database and then recreate the database.

Here's what I have so far:
     IF EXISTS(SELECT * FROM sys.databases WHERE NAME='[MyDatabase]')
     BEGIN
       ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
     DROP DATABASE [MyDatabase];
       END
       ELSE
     BEGIN
       CREATE DATABASE [MyDatabase]
       END

When I run this I get the error:
Database 'MyDatabase' already exists.  Choose a different database name.

Whut?

TIA!
LVL 1
ttist25Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
The brackets are not in the name:

 IF EXISTS(SELECT * FROM sys.databases WHERE NAME='MyDatabase') --<<-- note brackets removed from name

Btw, much,much better and safer to set the db offline rather than to single_user.  If a user happens to be in the db at the time, you may not be able to drop it.

ALTER DATABASE [MyDatabase] SET OFFLINE WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [MyDatabase] SET ONLINE;
DROP DATABASE [MyDatabase];
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ttist25Author Commented:
Man Scott.  It seems like you're saving my butt daily!!!!

I'm using pyodbc and a python script to do this work and reading in the table name as a variable there.  I surrounded the variable with brackets thinking it would save me time.  

HAH!  

Thanks again!!!!!

PS thanks for the "offline" tip
0
Scott PletcherSenior DBACommented:
You're welcome!!  Glad it helped.

You can get into SINGLE_USER hell sometimes, where you can't access the db for several minutes.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.