SQL Server Set a Database Offline and Online


Do you need to run a command in SSMS that sets a database to offline or online. You may need to take a database offline so that you can move the two database files to a different location. It’s easy to do. To take a database offline you can use this command, substituting the database name in for MyDataB. ALTER DATABASE myDataB SET OFFLINE

To set it back online, just change OFFLINE in the above command to ONLINE.

Suppose you wanted to set a bunch of databases online or offline. How could you do that? You could run the script below.

SELECT 'ALTER DATABASE [' + name + '] SET OFFLINE;'
FROM sys.databases
WHERE name NOT LIKE '%master%' AND
name NOT LIKE '%model%' AND
name NOT LIKE '%msdb%' AND
name NOT LIKE '%tempdb%' 

You can now just copy and paste the result into another Query window and run that query.