Created
July 7, 2011 20:10
-
-
Save rgl/1070433 to your computer and use it in GitHub Desktop.
Recreate (drop and create) an SQL Server Database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Recreate (drop and create) an SQL Server Database. | |
// | |
// NB: This will place the database in single mode (also rolling back current transactions). | |
// | |
// usage: RecreateDatabase(@"Data Source=.\SQLServer; Initial catalog = ESB_Store_Development; Integrated Security=True;"); | |
private static void RecreateSqlServerDatabase(string connectionString) | |
{ | |
const string databaseNameRegexPattern = @"(;\s*Initial Catalog\s*=\s*)([^;]+)\s*"; | |
var masterConnectionString = Regex.Replace(connectionString, databaseNameRegexPattern, "$1master", RegexOptions.IgnoreCase); | |
if (connectionString == masterConnectionString) | |
throw new ApplicationException("Oh, the master connection string is the same as the regular one?! fix that!"); | |
var databaseName = Regex.Match(connectionString, databaseNameRegexPattern, RegexOptions.IgnoreCase).Groups[2].Value; | |
using (var connection = new SqlConnection(masterConnectionString)) | |
{ | |
connection.Open(); | |
using (var command = connection.CreateCommand()) | |
{ | |
command.CommandText = string.Format("select count(*) from sys.databases where name='{0}'", databaseName); | |
var number = Convert.ToInt32(command.ExecuteScalar()); | |
if (number != 0) | |
{ | |
command.CommandText = string.Format("alter database {0} set single_user with rollback immediate", databaseName); | |
command.ExecuteNonQuery(); | |
command.CommandText = string.Format("drop database {0}", databaseName); | |
command.ExecuteNonQuery(); | |
} | |
command.CommandText = string.Format("create database {0}", databaseName); | |
command.ExecuteNonQuery(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment