0

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

4

2 回答 2

0

GO 是仅由 Sql Server Management Studio 无法解析的语句分隔符。
您的 C# 代码不能通过 ExecuteNonQuery 在语句中使用。只需删除它并确保每个语句都以分号结尾

sqlDropDBQuery = string.Format("EXEC msdb.dbo.sp_delete_database_backuphistory " + 
                 "@database_name = N'{0}';USE [master];" + 
                 "ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;" +
                 "USE [master];DROP DATABASE [{0}];", databaseName);
于 2013-10-10T08:14:08.070 回答
0

你可以试试这个。一

var s =string. Format( @"EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'{0}';

    USE master;

    ALTER DATABASE {0} SET  SINGLE_USER WITH ROLLBACK IMMEDIATE




    DROP DATABASE {0}",yourdbname);
于 2013-10-10T08:23:13.610 回答