Ошибка 3702 sql server

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?

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

DROP Database SQL Server

Let’s learn how to Drop Database in SQL Server when the users are connected to the SQL Server Database.

You may find the need to close all the existing database connections in a database before restoring the database, before detaching the database and for this, you need to get the database in SINGLE_USER mode.

If you ever try to drop a database when users are connected to the SQL Server Database then you will receive the below mentioned error message.

Error Message

Drop failed for Database 'MyTechMantra'. (Microsoft.SqlServer.Smo)
Cannot drop database "" because it is currently in use. (Microsoft SQL Server, Error: 3702)
Cannot drop database because it is currently in use Microsoft SQL Server Error 3702 

The reason why you end up getting the above-mentioned error is when SQL Server is Unable to Get Exclusive Access to SQL Server Database.

Warning: Be careful before executing Drop Database TSQL Command (More commonly used terminology is to Database Drop). Follow the steps mentioned in this article & learn How to Delete Database in SQL Server

Most commonly, to drop a database, it is referred to as “sql drop db“, “drop db” or “dropdatabase“. However, the correct syntax to Drop Database in SQL Server is DROP DATABASE

However, DROP DATABASE Command will fail when other users are already connected to the database. Check the example mentioned below in the article to understand How to Drop a Database by Killing Existing Connections.

Different Ways to Get Exclusive Access to Drop Database in SQL Server (SQL Server DROP Database)

  • Drop Database SQL Server Using SQL Server Management Studio (SSMS)
  • Drop Database SQL Server Using TSQL Query

Drop Database in SQL Server Using SQL Server Management Studio

  1. Connect to SQL Server Management Studio; expand Database Node -> Right click the Databases which you want to Drop -> Select Delete from the drop-down menu to open up Delete Object dialog box as shown in the snippet below.

Close Existing Connection in an SQL Server Database before Restoring the Database

2.

2. Select the Check box “Close existing connections” to Drop Existing Connections before Dropping the SQL Server Database and click OK to Drop Database in SQL Server.

3. By selecting “Delete backup and restore history information for databases” option you will be able to remove the database backup and restore history which is stored in MSDB system database.

Drop Database SQL Server Using TSQL Query

Execute the below TSQL code to Drop Database in SQL Server Using TSQL Query.

/* Delete Database Backup and Restore History from MSDB System Database */

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'MyTechMantra'
GO

/* Query to Get Exclusive Access of SQL Server Database before Dropping the Database  */

USE [master]
GO
ALTER DATABASE [MyTechMantra] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

/* Query to Drop Database in SQL Server  */

DROP DATABASE [MyTechMantra]
GO

Conclusion

In the article, you have seen different ways by which you can in SQL Server Drop Database by getting exclusive access to SQL Server Database.

Trending SQL Server Tips

  • SQL Delete Duplicate Rows from a SQL Table in SQL Server
  • How to Configure an SPN for SQL Server Site Database Servers
  • Register a Service Principal Name for Kerberos Connections
  • How to troubleshoot the “Cannot generate SSPI context” error message
  • How to use Kerberos authentication in SQL Server
  • Download Microsoft Kerberos Configuration Manager for SQL Server – A diagnostic tool that helps troubleshoot Kerberos related connectivity issues with SQL Server and SQL Server Reporting Services

Ashish Mehta

Ashish Kumar Mehta is a database manager, trainer and technical author. He has more than a decade of IT experience in database administration, performance tuning, database development and technical training on Microsoft SQL Server from SQL Server 2000 to SQL Server 2014. Ashish has authored more than 325 technical articles on SQL Server across leading SQL Server technology portals. Over the last few years, he has also developed and delivered many successful projects in database infrastructure; data warehouse and business intelligence; database migration; and upgrade projects for companies such as Hewlett-Packard, Microsoft, Cognizant and Centrica PLC, UK. He holds an engineering degree in computer science and industry standard certifications from Microsoft including MCITP Database Administrator 2005/2008, MCDBA SQL Server 2000 and MCTS .NET Framework 2.0 Web Applications.

  • 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

Msg 3702, Level 16, State 3, Line 2
Cannot drop database “DataBaseName” because it is currently in use.

This is a very generic error when DROP Database is command is executed and the database is not dropped. The common mistake user is kept the connection open with this database and trying to drop the database.

The following commands will raise above error:

USE AdventureWorks;
GO
DROP DATABASE AdventureWorks;
GO



Fix/Workaround/Solution:
The following commands will not raise an error and successfully drop the database:

USE Master;
GO
DROP DATABASE AdventureWorks;
GO

If you want to drop the database use master database first and then drop the database.

Reference : Pinal Dave (https://blog.sqlauthority.com)

Related Posts

Понравилась статья? Поделить с друзьями:
  • Ошибка 3701 рено премиум
  • Ошибка 37 вайм ворлд что делать
  • Ошибка 36h некорректные параметры
  • Ошибка 3699 мерседес
  • Ошибка 369 при оплате картой