Question

If I wish to take an MS Sql 2008 offline or online, I need to use the GUI -> DB-Tasks-Take Online or Take Offline.

Can this be done with some sql script?

Was it helpful?

Solution

ALTER DATABASE database-name SET OFFLINE

If you run the ALTER DATABASE command whilst users or processes are connected, but you do not wish the command to be blocked, you can execute the statement with the NO_WAIT option. This causes the command to fail with an error.

ALTER DATABASE database-name SET OFFLINE WITH NO_WAIT

Corresponding online:

ALTER DATABASE database-name SET ONLINE

OTHER TIPS

-- Take all user databases offline
CREATE PROCEDURE SP_TakeOfflineAllDatabase AS
BEGIN
    DECLARE @db sysname, @q varchar(max);
    DECLARE cur_db CURSOR FOR
        SELECT name FROM sys.databases WHERE owner_sid<>0x01;
    OPEN cur_db;
    WHILE 1=1
    BEGIN
        FETCH NEXT FROM cur_db INTO @db;
        IF @@FETCH_STATUS <> 0
            BREAK;
        SET @q = N'ALTER DATABASE [' + @db + N'] SET OFFLINE WITH NO_WAIT';
        EXEC(@q);
    END;
    CLOSE cur_db;
    DEALLOCATE cur_db;
END;

Restart the server before run the procedure. It will close the existed connections to the databases.

Here's a note that just might be very usefull to you : It's almost always possible to see what the GUI is doing TSQLwise behind the scenes.

c : http://www.mssqltips.com/tip.asp?tip=1505

I know this is an old post but, just in case someone comes across this solution and would prefer a non cursor method which does not execute but returns the scripts. I have just taken the previous solution and converted it into a select that builds based on results.

DECLARE @SQL VARCHAR(8000)

SELECT @SQL=COALESCE(@SQL,'')+'ALTER DATABASE  '+name+ N' SET OFFLINE WITH NO_WAIT;
    '
FROM sys.databases
WHERE owner_sid<>0x01
PRINT @SQL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top