Published on

January 25, 2020

How to Take a SQL Server User Database Offline

There may be instances where you need to take a SQL Server user database offline. This could be due to various reasons, such as testing if a database is still in use before dropping it or ensuring that a user cannot access an old database after it has been moved to a new server. In this article, we will explore three different methods to take a SQL Server user database offline.

Method 1: SQL Server Management Studio (SSMS)

The first method involves using SQL Server Management Studio (SSMS), a GUI-based tool that provides an easy and quick way to take a database offline. Here are the steps:

  1. Open SQL Server Management Studio.
  2. Connect to the database engine.
  3. Expand the server and databases dropdown.
  4. Right-click on the database you want to take offline and select “Tasks” > “Take Offline”.
  5. If the status is “Ready”, there are no connections in the database. If the status is “Not Ready”, click on the “Message” link to see the connections.
  6. To force connections out of the database, you can either manually kill the connections using T-SQL or check the “Drop All Active Connections” box in the “Take Database Offline” window.
  7. Verify that the database shows as “Offline” in the Object Explorer.

Method 2: T-SQL

The second method involves using T-SQL, which is a query language used in SQL Server. Here are the steps:

  1. Open SQL Server Management Studio.
  2. Right-click on the server and select “New Query”.
  3. Execute the command “EXEC sp_who2” to see the connections in the database.
  4. Kill the connections using the “kill” command with the corresponding SPID.
  5. Execute the command “ALTER DATABASE [MyDatabase] SET OFFLINE” to take the database offline.
  6. Verify that the database is offline by checking the “state_desc” column in the sys.databases table.

Method 3: dbatools

The third method involves using dbatools, a PowerShell module for SQL Server administration. Here are the steps:

  1. Open PowerShell.
  2. Run the command “Get-DbaProcess -SqlInstance [ServerName] -Database [DatabaseName] | Select Host, Login, Program” to see the connections in the database.
  3. If you are sure you can kill the connections, run the command “Get-DbaProcess -SqlInstance [ServerName] -Database [DatabaseName] | Stop-DbaProcess” to kill the connections.
  4. Run the command “Set-DbaDbState -SqlInstance [ServerName] -Database [DatabaseName] -Offline” to take the database offline.
  5. Verify that the database is offline.

These are three different methods you can use to take a SQL Server user database offline. Choose the method that best suits your needs and ensure that you backup the database and test restoring it before proceeding.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.