Monday, 18 March 2019

How to take all database offline at one in SQL Server

Hi All,

Today, we are going to learn how we can take all the Databases offline at one time by using SQL scripts. 

Below are the SQL scripts. 


DECLARE @dbName SYSNAME
,@query VARCHAR(MAX);
DECLARE cursor_db CURSOR
FOR
SELECT name
FROM sys.databases
WHERE owner_sid <> 0x01;
OPEN cursor_db;
WHILE 1 = 1
BEGIN
FETCH NEXT
FROM cursor_db
INTO @dbName;
IF @@FETCH_STATUS <> 0
BREAK;
SET @query = N'ALTER DATABASE [' + @dbName + N'] SET OFFLINE WITH NO_WAIT';
EXEC (@query);
END;
CLOSE cursor_db;
DEALLOCATE cursor_db;


Thanks for reading.