Last active
June 13, 2024 22:33
-
-
Save alivarzeshi/af528c2037c40034c1f5d3542a28fa58 to your computer and use it in GitHub Desktop.
T-SQL Script to Take All User Databases Offline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @dbName NVARCHAR(255) | |
DECLARE @sql NVARCHAR(MAX) | |
-- Create a cursor to iterate over all databases except system databases | |
DECLARE db_cursor CURSOR FOR | |
SELECT name | |
FROM sys.databases | |
WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb') -- Exclude system databases | |
OPEN db_cursor | |
FETCH NEXT FROM db_cursor INTO @dbName | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
-- Construct the dynamic SQL statement to take the database offline | |
SET @sql = 'ALTER DATABASE [' + @dbName + '] SET OFFLINE WITH ROLLBACK IMMEDIATE;' | |
-- Execute the dynamic SQL statement | |
EXEC sp_executesql @sql | |
-- Fetch the next database name | |
FETCH NEXT FROM db_cursor INTO @dbName | |
END | |
-- Close and deallocate the cursor | |
CLOSE db_cursor | |
DEALLOCATE db_cursor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To take all databases offline in a SQL Server instance using T-SQL, you can create a script that iterates over all databases and sets each one to the OFFLINE state. Here's a T-SQL script to accomplish this:
Explanation:
Cursor Declaration:
db_cursor
is declared to iterate over all database names in thesys.databases
catalog view, excluding the system databases (master
,model
,msdb
,tempdb
).Cursor Open and Fetch:
@dbName
variable.While Loop:
WHILE
loop runs as long as there are database names to process (@@FETCH_STATUS = 0
).Dynamic SQL Construction:
WITH ROLLBACK IMMEDIATE
clause is used to immediately rollback any active transactions and forcefully disconnect all users from the database.SQL Execution:
sp_executesql
.Fetch Next:
@dbName
variable.Cursor Closure and Deallocation:
Note: Be very careful when running this script, especially on a production server, as it will forcefully take all user databases offline. Always ensure you have appropriate backups and have notified relevant stakeholders before executing such operations.