Lately I have been finding myself restoring a DB to my local instance of SQL-server a lot more. I wanted to speed up the process by writing a script and then just executing it in order to restore over some X DB on my local. However, every time that I run this script I get the error saying the DB is still being used. Now this could happen because I have a query open, or because a web application is still using it, but instead of me going to track down what is using my db and stopping it. I would much rather have my script take care of this since this is not going to be affecting anyone but me.
Is there a better way to do this than querying for the processes that are using the DB and killing them? Currently I was thinking of doing the following
select
spid,status,loginame=SUBSTRING(loginame,1,12),
hostname=SUBSTRING(hostname,1,12),
dbname = SUBSTRING(db_NAME(dbid),1,10)
from sys.sysprocesses where DBid = 17
and then running the results back through a dynamic sql with the KILL command.
Best Answer
You can set the database in
SINGLE_USER
mode. If you also specifyROLLBACK IMMEDIATE
it won't wait for open transactions to finish but will just roll them back.