Cannot drop database because it is currently in use microsoft sql server ошибка 3702

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.

Cannot drop database because it is currently in use in MS SQL Server

 You can avoid this error by checking the option Close existing connections.

Cannot drop database because it is currently in use- Close existing connections

Thanks,
Morgan
Software Developer

  • 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

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 enfironements. 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 DATABASE command.

Guide to fix the SQL Server error Cannot drop the database

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. This other article is about how to create a database with default options with the SSMS graphic user interface. The exact error message text is the folowwing:

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.

This type of script generates the error:

USE [master];
GO

DROP DATABASE [DB1];
GO

Another way is to check the database existence 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 :

1. Execute the sp_who2 procedure to identify SPID of active sessions

In the screenshot we identify the active sessions for the DB1 database. We see one user with SPID 51.

sp_who2

Run the sp_who2 command to fix the SQL Server error 3702

Run the sp_who2 command to fix the SQL Server error 3702

2. Close sessions with the SQL Server kill command and SPID

It is the active SPID that prevent the database to be dropped. Indeed, the RDBMS do not allow to drop a database with active sessions.

2.1 Terminate all the sessions with the SPIDs found

Use the Server Process ID (SPID) found in the previous query to kill the session. Execute the query in SSMS.

kill 51

Use the kill procedure to terminate the session with the SPID identified earlier

Use the kill procedure to terminate the session with the SPID identified earlier

2.2 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 dropping 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.

https://expert-only.com/en/sql-server-db/empty-the-sql-server-transaction-log-and-fix-error-9002/

SQL Server administration tutorials

To go further and learn more on database, find more tutorials on the SQL Server database administration 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?

I faced this type of problem when working with Sql Server Management Studio. After many days of googling and experiments, i finally found an issue.

NB: You ought to firstly create a drop and create table script for this table, if not you will not have your table

1-First create only yours tables with theirs coresponding foreign keys.

2-Create a visual diagram with these table (Sql express-Databases-Databasename-DataBase Diagram-Right click on it and select new database diagram)

3-Add the required datatables on diagram and create the relation between these datatables with corresponding foreign keys added during the creation of tables

4-Then saved your Database

In the case that you have forget to add a given field in a datatable, you can easily drop and create your datatables, to do this, follow these steps:

1-Open the Database diagram of the corresponding database

2-delete all the relationships which exist between the old table to which you want to add some field and others tables

3-then delete the corresponding table from diagram(right click on the table , then select delete table from the datatable)

4-Save the diagram (Ctrl +S)

5-go to the table that you want to drop and create

6-Right click on the table and select( Script table as then select drop and create then go to new Query editor windows), this will script your table in new table, at this time you can modify it to your need, exemple with and old and new same table

Old table

        USE [DatabaseName]
      GO

         /****** Object:  Table [dbo].[Administrateur]    Script Date:  10/11/2016 2:06:04 PM ******/
      DROP TABLE [dbo].[Administrateur]
     GO

      /****** Object:  Table [dbo].[Administrateur]    Script Date: 10/11/2016 2:06:04 PM ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

   CREATE TABLE [dbo].[Administrateur](
[AdministrateurID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Surname] [nvarchar](max) NULL,
[Phone] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NOT NULL,
[Sexe] [nvarchar](max) NOT NULL,

 CONSTRAINT [PK_Administrateur] PRIMARY KEY CLUSTERED 
 (
[AdministrateurID] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =    OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

 GO

Now the NEW SAME TABLE WITH 3 NEW FIELDS(Email, Image and Salt)

   USE [DatabaseName]
   GO

    /****** Object:  Table [dbo].[Administrateur]    Script Date: 10/11/2016 2:06:04 PM ******/
  DROP TABLE [dbo].[Administrateur]
  GO

   /****** Object:  Table [dbo].[Administrateur]    Script Date:    10/11/2016 2:06:04 PM ******/
  SET ANSI_NULLS ON
  GO

  SET QUOTED_IDENTIFIER ON
  GO

   CREATE TABLE [dbo].[Administrateur](
[AdministrateurID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Surname] [nvarchar](max) NULL,
[Phone] [nvarchar](max) NOT NULL,
[Email] [nvarchar](max) NOT NULL,
[Username] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NOT NULL,
[Image] [nvarchar](max) NOT NULL,
[Sexe] [nvarchar](max) NOT NULL,
[Salt] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_Administrateur] PRIMARY KEY CLUSTERED 
  (
   [AdministrateurID] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =    OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Then in the page of the modified Datatable, Press Execute. It will not execute for the first time and will write some errors encountered, but don’t care and just press Execute in second time. At this time, it will execute and write the success message at the bottom of the document.Then select the database and click on Refresh (or press F5), he will update your Database’s tables in some computer or you will need to restart the program before seing the updates in others computers(I don’t know why, so don’t ask me to explain).

Go back now to the diagram and dd the updated table and then connect these(this) table(s) to the tables which has any relation with it.

Hope that this will save the time of someones.

I don

  • Remove From My Forums
  • Question

  • Dear colleagues,

    I use SQL Server 2012. The exact version info is:

    Microsoft SQL Server 2012 — 11.0.2100.60 (X64)   Feb 10 2012 19:39:15   Copyright (c) Microsoft Corporation  Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor) 

    I am flabbergasted. I try to drop a database, but that won’t work because it says it is in use. But it isn’t. I think I should no what to do, but actually I don’t. Below, the SQL I use. Per statement, in the comment below, you can see the result. I cancelled
    the ‘SET SINGLE_USER WITH ROLLBACK IMMEDIATE’ after 4 minutes because nothing happened. This probably points to the real problem, but I cannot think what it is.

    Kind Regards,

    Chris Sijtsma

    USE [master]
    GO
    
    EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'Start10_64892_DB';
    -- Commands completed successfully.
    -- Completion time: 2020-04-15T07:09:32.7893007+02:00
    GO
    
    DROP DATABASE [Start10_64892_DB];
    -- Msg 3702, Level 16, State 4, Line 9
    -- Cannot drop database "Start10_64892_DB" because it is currently in use.
    -- Completion time: 2020-04-15T07:10:10.1496410+02:00
    GO
    
    SELECT COUNT(1) FROM master.sys.sysprocesses p WHERE p.dbid = DB_ID(N'Start10_64892_DB');
    -- Returns the value 0
    GO
    
    ALTER DATABASE [Start10_64892_DB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    --      :
    -- Nonqualified transactions are being rolled back. Estimated rollback completion: 0%.
    -- Nonqualified transactions are being rolled back. Estimated rollback completion: 0%.
    -- Msg 5069, Level 16, State 1, Line 10
    -- ALTER DATABASE statement failed.
    -- Query was canceled by user.
    GO

Answers

  • Microsoft SQL Server 2012 — 11.0.2100.60 (X64)   Feb 10 2012 19:39:15 

     Copyright (c) Microsoft Corporation  Standard Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor) 

    SQL 2012 SP1. It may or may not resolve the issue, but for all candy in the world, please apply SP4! (Well, since the requires you to restart SQL Server, it will probably resolve this problem automatically.)


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Marked as answer by

      Wednesday, April 15, 2020 6:50 AM

Возможно, вам также будет интересно:

  • Cannot copy extracted data for ошибка cydia
  • Cannot communicate with server ошибка
  • Cannot be resolved to a variable java ошибка
  • Cannot be resolved to a type ошибка java
  • Cannot assign without a target object ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии