RSS

Bring SQL Server Database Offline using Script

29 Dec

To bring any database offline immediately you should first stop all processes on this database then bring it offline otherwise you can’t bring database before stop all processes on this database.

Code bellow give your database offline immediately

declare @dbname nvarchar(10)

set @dbname =‘AdventureWorks’

Select SPID into #temp From master.dbo.sysprocesses where [DBID]=DB_ID(@dbname)

Select SPID From master.dbo.sysprocesses where DB_ID(@dbname)=[DBID]

DECLARE @spid INT

DECLARE @getspid CURSOR

DECLARE @tString varchar(8000)

Set @getspid = Cursor For Select SPID from #temp

OPEN @getspid

FETCH NEXT FROM @getspid INTO @spid WHILE @@FETCH_STATUS = 0

BEGIN

SET @tString = ‘KILL ‘ + CAST(@spid AS VARCHAR(5))

EXEC(@tString)

FETCH NEXT FROM @getspid INTO @spid END

CLOSE @getspid

DEALLOCATE @getspid

exec sp_dboption @dbname, ‘offline’, ‘true’

 

Select SPID From master.dbo.sysprocesses where DB_ID(@dbname)=[DBID]  

Drop table #temp

 

 

 

Advertisements
 
Leave a comment

Posted by on December 29, 2009 in SQLAdmin, SQLServer, T-SQL

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: