Question: I have an SQL script which backs up a database and then restores it over another database. the problem I'm having is that the database being overwritten is being locked open by a user so the job fails. I can manually kill the attached user and it runs fine but I need this process to run automatically every night. Is there a kill command which I can time to execute every night? or is there something in the restore options to do the same thing?

Any thoughts?

Thanks

Answer: 
KILL isn't always effective if the client reconnects

I'd consider taking the database offline (or dbo only) then restoring. Thus will prevent further reconnects.

```
ALTER DATABASE TargetDB SET OFFLINE WITH ROLLBACK IMMEDIATE 

```

or

```
ALTER DATABASE TargetDB SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE 

```
```
DECLARE @pid AS INTEGER

DECLARE mycursor CURSOR FOR
select spid 
from sys.sysprocesses
WHERE dbid = DB_ID('yourdatabasename')

OPEN mycursor 
FETCH NEXT FROM mycursor INTO @pid

WHILE @@FETCH_STATUS = 0
BEGIN
EXECUTE ('KILL '+@pid)
FETCH NEXT FROM mycursor INTO @pid
END

CLOSE mycursor
DEALLOCATE mycursor

```