introduction
In the project, by using the SQL statement "DROP DATABASE [database name]" When you delete data, it has been the error message "Unable to delete database" XXXX ", because the database is currently in use", tested SqlSever database client in, direct the implementation of the Sql statement can be executed properly, but through OLEDB execute the Sql statement appeared in the above error, the author access to relevant documents, found a solution to this problem.
Solution
The library is set to be deleted database in single user mode and settings immediately rollback the specific SQL statement is as follows:
USE [master] ALTER DATABASE [database name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE DROP DATABASE [database name]
Packaging delete the database as follows:
public static bool DeleteSqlServerDB(string serverCon, string dbName) { bool bSuccess = false; try { using (SqlConnection conMaster = new SqlConnection(serverCon)) { conMaster.Open(); string strExist = @"select * from dbo.sysdatabases where name='" + dbName + @"'"; SqlCommand cmdExist = new SqlCommand(strExist, conMaster); SqlDataReader readerExist = cmdExist.ExecuteReader(); bool bExist = readerExist.HasRows; readerExist.Close(); if (bExist) { var cmd = new SqlCommand( $" USE [master] ALTER DATABASE [{dbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE DROP DATABASE [{dbName}]", conMaster); cmd.ExecuteNonQuery(); } conMaster.Close(); } bSuccess = true; } catch (Exception e) { bSuccess = false; } return bSuccess; }
Note: SqlCommand can perform a number of sql statement, sql statements directly with each space or ";" to separate.
to sum up
In the process of database operations, we will encounter strange errors, continuous learning and summed up is the only way for us to enter the next stage! If this article helpful to you, please support the next attention!