SQL Detach Database

Let us see the steps involved to detach database in SQL Server. To demonstrate this database deletion, we are going to use the existing stored procedure and Management Studio.

SQL Detach Database Approach

From the below screenshot, you can see that the SQL server have the AdventureWorks2017

View Databases in Management Studio 1

It has a sp_detach_db stored procedure to detach the database. The syntax for this is

EXEC sp_detach_db N'Database Name', 'true';

Let me use the above syntax to delete AdventureWorks 2017.

EXEC sp_detach_db N'AdventureWorks2017', 'true';
Messages
-------
Commands completed successfully.

Now you can see the Adventure Works 2017 removed from our Server

SQL Detach Database 3

Detach Db Approach 2

You can also use Management Studio to detach the database. To do so, Right-click on the Databases folder and select the Tasks option and then select Detach.. from the context menu.

CHoose Tasks and Detach Option from context menu 5

Clicking the option will open the following window to detach a database in SQL Server.

  • DatabaseName: This will display the Name that you want to delete.
  • Drop Connections: Checkmark this option to drop all the existing connections pointing to this db.
  • Update Statistics: Checkmark this option to update existing optimization statistics.
SQL Detach Database 6

Checkmark the Drop Connections, and Click Ok

SQL Detach Database 7

The Adventure Works DW 2017 deleted from the Server

SQL Detach Database 8

The above process will only detach or remove the database from SQL Server, but it will keep the MDF, and LDF files within the physical location (C Drive).

SQL Detach Database 9