Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Script to Stop a db or take it offline 2

Status
Not open for further replies.

GrandMauler

Programmer
May 16, 2007
74
US
Hello.

I'm looking for an SQL command to either stop a db or take it offline or drop all the current users so that I can detach a db.


Any help?

Thanks in advance
 
You could try:
Code:
[COLOR=blue]ALTER[/color] [COLOR=blue]DATABASE[/color] [databasename] [COLOR=blue]SET[/color] [COLOR=blue]OFFLINE[/color] [COLOR=blue]WITH[/color] [COLOR=blue]ROLLBACK[/color] [COLOR=blue]IMMEDIATE[/color]


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
This will kill all the users in a database. I wouldn't take a database off-line just to kill user connections.

Code:
DECLARE @strSQL varchar(255)
PRINT 'Killing Users'
PRINT '-----------------'

CREATE table #tmpUsers(
spid int,
eid int,
status varchar(30),
loginname varchar(50),
hostname varchar(50),
blk int,
dbname varchar(50),
cmd varchar(30),
requestid int)

INSERT INTO #tmpUsers EXEC SP_WHO


DECLARE LoginCursor CURSOR
READ_ONLY
FOR SELECT spid, dbname FROM #tmpUsers WHERE dbname = '[b]<yourdb>[/b]'

DECLARE @spid varchar(10)
DECLARE @dbname2 varchar(40)
OPEN LoginCursor

FETCH NEXT FROM LoginCursor INTO @spid, @dbname2
WHILE (@@fetch_status <> -1)
BEGIN
        IF (@@fetch_status <> -2)
        BEGIN
        PRINT 'Killing ' + @spid
        SET @strSQL = 'KILL ' + @spid
        EXEC (@strSQL)
        END
        FETCH NEXT FROM LoginCursor INTO  @spid, @dbname2
END

CLOSE LoginCursor
DEALLOCATE LoginCursor

DROP table #tmpUsers


GO

- Paul
- If at first you don't succeed, find out if the loser gets anything.
 
Both very attractive suggestions which I will explore fully.


Thanks, guys.


Gave both of you a star.


Cheers!
 
Just out of curiosity, Paul, why would you advice against the "Offline" option?
 
I don't use the off-line method because it can take a long time to set the database off line. I run the kill command then I set the db in single user. (same as Denis.)

- Paul
- If at first you don't succeed, find out if the loser gets anything.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top