Description
In this article, I am going to give Fix/Solution for the error ‘Cannot drop database because it is currently in use’ in MS SQL Server.. This error occurs when we try Delete or Drop database while the database connection is used by other users or other resources. So we need to close existing connections first then we need to Drop or Delete the database.
Summary
- Fix/Solution: Cannot drop database because it is currently in use in MS SQL Server in Script
- C# Fix/Solution: Cannot drop database because it is currently in use in MS SQL Server
- Fix/Solution in Management Studio: Cannot drop database because it is currently in use in MS SQL Server
USE [MorganDB] GO /****** Object: Database [MorganDB] Script Date: 11/29/2013 13:29:16 ******/ DROP DATABASE [MorganDB] GO
When you run above script, you will get an error message
‘Msg 3702, Level 16, State 4, Line 2
Cannot drop database “MorganDB” because it is currently in use.
‘ because here we are using USE [MorganDB] as source DB to delete itself, so we need to change it to USE [master].
Fix/Solution:
USE [master] GO /****** Object: Database [MorganDB] Script Date: 11/29/2013 13:29:16 ******/ DROP DATABASE [MorganDB] GO
Perfect Fix/Solution:
After changing source database as master, the script should works successfully. But sometimes connection may be opened by any other user. So, in that case, we also need to close existing open connections.
USE [master] GO ALTER DATABASE [MorganDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO USE [master] GO /****** Object: Database [MorganDB] Script Date: 11/29/2013 13:40:36 ******/ DROP DATABASE [MorganDB] GO
Fix/Solution in C#: Cannot drop database because it is currently in use in MS SQL Server
You can use the following C# code to close existing database connections and Drop or Delete Database in MS Sql Server.
public static void DeleteDataBase() { using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.sqlexpress;Initial Catalog=master;Integrated Security=SSPI;")) { sqlconnection.Open(); // if you used master db as Initial Catalog, there is no need to change database sqlconnection.ChangeDatabase("master"); string rollbackCommand = @"ALTER DATABASE [MorganDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"; SqlCommand deletecommand = new SqlCommand(rollbackCommand, sqlconnection); deletecommand.ExecuteNonQuery(); string deleteCommand = @"DROP DATABASE [MorganDB]"; deletecommand = new SqlCommand(deleteCommand, sqlconnection); deletecommand.ExecuteNonQuery(); } }
Fix/Solution in Sql Server Management Studio for the error ‘Cannot drop database because it is currently in use’ in MS SQL Server
If you try to dropping a database in Sql Server Management Studio UI when an user connected to the SQL Server Database you will receive the below mentioned error message.
You can avoid this error by checking the option Close existing connections.
Thanks,
Morgan
Software Developer
How to fix the SQL Server error Cannot drop the database because it is currently in use?
Also know as the 3702 error, the SQL Server error Cannot drop the database because it is currently in use is frequent in multi-user environments. It is possible to manage SQL databases with scripts or via the various windows of SQL Server Management Studio. For example, you can simply delete a database with a SQL DROP statement. However, if there are active connections on the database being deleted, then the database returns an error message, because a database with an active connection cannot be deleted.
1. Scripts that generates the drop database error
The exact error message text is the following:
Cannot drop database because it is currently in use. (Microsoft SQL Server, Error: 3702).
Note: Be careful to check the database backups before deleting it completely. Especially in important projects and production environments.
For example, this type of script generates the error:
USE [master]; GO DROP DATABASE [DB1]; GO
Another way to create the database is to check if the DB exist on the server, before running the Drop Database command, like this for example:
USE [master]; GO IF EXISTS ( SELECT name FROM master.dbo.sysdatabases WHERE name = 'DB1' ) DROP DATABASE [DB1]; GO
To avoid this error, close all active connections to the database before the drop and terminate the current queries. Then close the tabs in SSMS or explicitly end the open connections on the database. Finally close the active tabs if only one user is currently connected. For the second step, run these two operations :
2. Execute sp_who2 procedure to identify IDs of active sessions
In the screenshot we identify the active sessions for the DB1 database. We see one user with SPID 51.
sp_who2
Check out this other article about how to create a database with default options with the SSMS graphic user interface.
3. Close sessions with the SQL Server kill command and SPID
It is the active SPID that prevent the drop from being successful. Indeed, the Microsoft RDBMS do not allow to drop a database with active sessions. Indeed, you need to terminate all the sessions with the SPIDs found. To do this, use the Server Process ID (SPID) found in the previous query to kill the session. Execute the query in SSMS.
kill 51
4. Execute again the drop database script without error
Repeat the operation till no active connections are visible on the list. To go further, here is the official documentation of the T-SQL kill command. The “unable to drop the database because it is currently in use” sql command error is a classical one. Indeed it’s an object that allows many connections from different users at the same time.
Conclusion on SQL Server error 3702
This MS SQL tutorial explains how to avoid the common SQL Server error message : Cannot drop the database because it is currently in use. It is a common error and the tip is very useful when creating and deleting multiple databases in development and testing environments for example.
How to completely drop a SQL Server database ?
A database, unlike a table, cannot be erased or dumped. A database must be dropped, i.e., completely deleted to remove all its contents. Use the DROP DATABASE command to delete a SQL Server database.
SQL Server administration tutorials
To go further and learn more on MS databases management, check out this tutorials on the SQL Server DBA topic.
- Empty the SQL Server transaction log and fix error 9002
- How to install a second SQL Server instance on a server?
- How to display the SQL Server detailed version with a query?
- Remove From My Forums
-
Question
-
TITLE: Microsoft SQL Server Management Studio
——————————Drop failed for Database ‘ DBNAME’. (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
——————————
Cannot drop database » DBNAME» because it is currently in use. (Microsoft SQL Server, Error: 3702)
BUTTONS:
OK
——————————
Harry
Answers
-
Harry,
The error is saying that the database is currently being used. Personally I like to open up a new command window and issue an alter atabase to put it in single user mode then use that same connection to drop the database.
USE MASTER GO ALTER DATABASE {DB} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO DROP DATABASE {DB} GO
The WITH ROLLBACK IMMEDIATE tells SQL Server to rollback any uncommited transactions and terminate all connections, allowing only 1 (single user).
-Sean
-
Marked as answer by
Wednesday, August 31, 2011 12:21 AM
-
Marked as answer by
Problem
While trying to delete test database to, the user gets a use and encounters the error: «Error 3702: Cannot drop the database ‘cqtst’ because it is currently in use.»
Symptom
User gets message:
«Error 3702: Cannot drop the database ‘cqtst’ because it is currently in use.»
Cause
A second instance of the Designer and Enterprise manager where running at the same time. Once they where closed the user was able to proceed
Environment
ClearQuest 7.1.1.03
Windows Server 2003
SQL Server
Diagnosing The Problem
Check for open Designer sessions
Resolving The Problem
Close open sessions.
[{«Product»:{«code»:»SSSH5A»,»label»:»Rational ClearQuest»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Designer — Database Administration»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.1.1.3″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]
Просмотр полной версии : Проблема удаления баз Navision под MS SQL
Всем привет!
Периодически возникает такая ситуация, что нельзя удалить базы Navision 3.70 крутящиеся на MS SQL.
В Navision пишет что-то вроде 3702,Cannot drop the database Test because it is currently in use.
При этом сессий 0.
Через Enterprise MS SQL-a то же самое: сессий — 0, удалить — ошибка 3702, Detach Database не работает
Спасает только перезапуск MS SQL . Может кто знает как решить эту проблему?
Может надо сначала остановить сервер?
Спасает только перезапуск MS SQL
<{POST_SNAPBACK}>
так и я про тоже — сначала Stop, потом Start,
в этом методе напрягает то, что работающий народ «вываливается» …
Спасает только перезапуск MS SQL
<{POST_SNAPBACK}>
так и я про тоже — сначала Stop, потом Start,
в этом методе напрягает то, что работающий народ «вываливается» …
<{POST_SNAPBACK}>
Этот вопрос надо разместить на каком-нибудь сайте посвященном администрированию MS-SQL сервера. Но ответ, скорее всего будет, что так сделана архитектура сервера.
Удалось всё-таки найти способ «малой крови»
В Enterprise Manager-e через меню Locks/Process ID, либо Locks/Object нашлись процессы «держащие» базу — Kill и база готова к удалению
Вариант куда проще.
В Enterprise Manager’е нужно сделать Detach БД.
При этом сервер спросит уверены ли вы что вы выкидываете всех активных юзеров. Вы соглашаетесь. После этого БД можно спокойно удалять.
Вариант куда проще.
В Enterprise Manager’е нужно сделать Detach БД.
При этом сервер спросит уверены ли вы что вы выкидываете всех активных юзеров. Вы соглашаетесь. После этого БД можно спокойно удалять.
<{POST_SNAPBACK}>
«Через Enterprise MS SQL-a то же самое: сессий — 0, удалить — ошибка 3702, Detach Database не работает»
я писал про Detach — показывает сессий 0, вероятно механизм подсчета сессий, как и в Navision, через \Management\Current Activity\Process Info
Работает на vBulletin® версия 3.8.5. Copyright ©2000-2023, Jelsoft Enterprises Ltd. Перевод: zCarot