我正在研究C#中的一个解决方案,我可以在SQL Server 2008 R2 Express Edition中删除数据库。我搜索了WWW并找到了以下解决方案: Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)
我还尝试从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
这是我使用的代码:
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;
}
不幸的是,我总是得到一个例外:
'GO'附近的语法不正确。 'GO'附近的语法不正确。不正确 'GO'附近的语法。
我也试过没有逃脱\ n!
有什么建议吗?
谢谢, tro
答案 0 :(得分:0)
GO只是一个语句分隔符,只能由Sql Server Management Studio取消 不能通过ExecuteNonQuery在C#代码的语句中使用。 只需删除它,并确保每个语句都以分号结束
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);
答案 1 :(得分: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);