I want to write a script that allows me to connect to a sql db, create the db to a textfile and then drop then entire database. Once this is done I would like to be able to re-create the entire database. Is this possible?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the
Microsoft.SqlServer.Management.Smonamespace to generate a script, just like you would in ssms. It might take a few tries to get the ScriptingOptions right, so don’t get over zealous and start dropping things right away.Once you’ve generated your script, it would be a simple
ExecuteNonQuery("drop database foo")to drop your database.To recreate, use the same namespace to execute the script. Using a normal
ExecuteNonQuerywill not work because the script will contain “GO”, which is not valid sql. The SMO does contain logic to handle that though.This is assumed, of course, to be logged in with a user that has adequate permissions on the sql server.