Alex Rivera | Logout

SQL Script to take a Microsoft Sql database online or offline?

Asked 2009-05-11T07:29:22.353
12

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?

Edit
Report

2 Answers

19
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
answered 2009-05-11T07:32:32.207
4

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
answered 2012-04-04T07:14:57.870

Your Answer