简体   繁体   English

如何使用C#删除“正在使用”的SQl Server数据库?

[英]How To Delete SQl Server database while it is “In Use” using C#?

I am trying to delete sql server database. 我正在尝试删除sql server数据库。 It gets deleted if it is not in use. 如果不使用它将被删除。 If database is in use an exception occurred saying that can not delete database while it is in use . 如果数据库正在使用中,则会发生一个异常,说can not delete database while it is in use We can delete use database from management studio using option Close existing connection . 我们可以使用选项“ Close existing connection从Management Studio中删除使用数据库。 But how can we do this using C# code? 但是我们如何使用C#代码来做到这一点呢?

ALTER DATABASE AdventureWorks2012
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;

DROP DATABASE AdventureWorks2012;

Make a script file by writing above query in it.Then execute this script file as below : 通过在上面的查询中编写脚本文件,然后执行以下脚本文件:

string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
            FileInfo file = new FileInfo("C:\\myscript.sql");
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery(script);

The easy way on a MS SQL Server to kick all users off is: 在MS SQL Server上启动所有用户的简单方法是:

ALTER DATABASE [MyDB] SET Single_User WITH Rollback Immediate
GO

Fire this Query through your code and go ahead:- 通过您的代码触发此查询,然后继续:-

SOURCE:- 资源:-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM