I am working on a a solution in C# where I can DROP a Database in SQL Server 2008 R2 Express Edition. I searched the WWW and found the following solution: Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)
I also tried to create the script from the SQL Server:
EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'apm4reform'
GO
USE [master]
GO
ALTER DATABASE [apm4reform] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object: Database [apm4reform] Script Date: 10/10/2013 00:58:06 ******/
DROP DATABASE [apm4reform]
GO
Here my code I use:
private static bool DropDatabase(SqlConnection tmpConn, string connectionString, string databaseName)
{
string sqlDropDBQuery;
bool result = false;
try
{
tmpConn.ConnectionString = connectionString;
tmpConn.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = tmpConn;
sqlDropDBQuery = string.Format("EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'{0}'\n GO\n USE [master]\n GO\n ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO\n USE [master]\n GO\n DROP DATABASE [{0}]\n GO\n", databaseName);
thisCommand.CommandText = sqlDropDBQuery;
thisCommand.ExecuteNonQuery();
result = true;
}
catch (Exception ex)
{
result = false;
}
finally
{
tmpConn.Close();
}
return result;
}
Unfortunately, I always get an exception:
Incorrect syntax near 'GO'. Incorrect syntax near 'GO'. Incorrect syntax near 'GO'.
I also tried without the escapes \n!
Any suggestions?
Thanks, tro