Set database from SINGLE USER mode to MULTI USER - sql

I need help with setting a database that was restored in SINGLE_USER mode to MULTI_USER. Every time I run
ALTER DATABASE BARDABARD
SET MULTI_USER;
GO
I get this error:
Changes to the state or options of database 'BARDABARD' cannot be made at this time.
The database is in single-user mode, and a user is currently connected to it.
It needs to be in non-SINGLE_USER mode to set it to another mode, but I can’t set the database in any another mode while it is SINGLE_USER mode.

The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the ALTER query again.

That error message generally means there are other processes connected to the DB. Try running this to see which are connected:
exec sp_who
That will return you the process and then you should be able to run:
kill [XXX]
Where [xxx] is the spid of the process you're trying to kill.
Then you can run your above statement.

You can add the option to rollback your change immediately.
ALTER DATABASE BARDABARD
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO

SQL Server 2012:
right-click on the DB > Properties > Options > [Scroll down] State > RestrictAccess > select Multi_user and click OK.
Voila!

I had the same issue and it fixed by the following steps - reference: http://giladka8.blogspot.com.au/2011/11/database-is-in-single-user-mode-and.html
use master
GO
select
d.name,
d.dbid,
spid,
login_time,
nt_domain,
nt_username,
loginame
from sysprocesses p
inner join sysdatabases d
on p.dbid = d.dbid
where d.name = 'dbname'
GO
kill 56 --=> kill the number in spid field
GO
exec sp_dboption 'dbname', 'single user', 'FALSE'
GO

This worked fine for me.
Step 1. Right click on database engine, click on activity monitor and see which process is having connection. Kill that particular user and execute the query Immediately.
Step 2.
USE [master];
GO
ALTER DATABASE [YourDatabaseNameHere] SET MULTI_USER WITH NO_WAIT;
GO
and refresh the database.

I have just fixed using following steps, It may help you.
Step: 1
Step: 2
Step: 3
Step: 4
Step: 5
Then run following query.
ALTER DATABASE YourDBName
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO
Enjoy...!

I actually had an issue where my db was pretty much locked by the processes and a race condition with them, by the time I got one command executed refreshed and they had it locked again... I had to run the following commands back to back in SSMS and got me offline and from there I did my restore and came back online just fine, the two queries where:
First ran:
USE master
GO
DECLARE #kill varchar(8000) = '';
SELECT #kill = #kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('<yourDbName>')
EXEC(#kill);
Then immediately after (in second query window):
USE master ALTER DATABASE <yourDbName> SET OFFLINE WITH ROLLBACK IMMEDIATE
Did what I needed and then brought it back online. Thanks to all who wrote these pieces out for me to combine and solve my problem.

It may be best to log onto the server directly instead of using SQL Management Studio
Ensure that the account you login as is dbowner for the database you want to set to MULTI_USER. Login as sa (using SQL server authentication) if you can
If your database is used by IIS, stop the website and the app pool that use it - this may be the process that's connected and blocking you from setting to MULTI_USER
USE MASTER
GO
-- see if any process are using *your* database specifically
SELECT * from master.sys.sysprocesses
WHERE spid > 50 -- process spids < 50 are reserved by SQL - we're not interested in these
AND dbid=DB_ID ('YourDbNameHere')
-- if so, kill the process:
KILL n -- where 'n' is the 'spid' of the connected process as identified using query above
-- setting database to read only isn't generally necessary, but may help:
ALTER DATABASE YourDbNameHere
SET READ_ONLY;
GO
-- should work now:
ALTER DATABASE Appswiz SET MULTI_USER WITH ROLLBACK IMMEDIATE
Refer here if you still have trouble:
http://www.sqlservercentral.com/blogs/pearlknows/2014/04/07/help-i-m-stuck-in-single-user-mode-and-can-t-get-out/
AS A LAST ALTERNATIVE - If you've tried everything above and you're getting desperate you could try stopping the SQL server instance and start it again

You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working.
Just do that: Close management studio and re open it. new query window without selecting any database write the command script.
USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO
make f5 wolla everything ok !

The code below has worked for me when I didn't know the specific SPID that was used to change into singleuser mode.
use master
GO
select
d.name,
d.dbid,
spid,
login_time,
nt_domain,
nt_username,
loginame
from sysprocesses p
inner join sysdatabases d
on p.dbid = d.dbid
where d.name = 'dbname'
GO
kill 52 -- kill the number in spid field
GO
exec sp_dboption 'dbname', 'single user', 'FALSE'
GO

Tried everything didn't work
Login to that server remotely as we gonna kill all connections
run the below code more than once till it returns completed and no "killing process" test anymore
reactivate it again using the code below the below code
use master GO declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid =
db_id('DB_NAME') and spid != ##spid
while (#spid is not null) begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
dbid = db_id('DB_NAME')
and spid != ##spid end
then to bring it back alive
ALTER DATABASE DB_NAME SET MULTI_USER; GO

This worked fine for me
Take a backup
Create new database and restore the backup to it
Then Properties > Options > [Scroll down] State > RestrictAccess > select Multi_user and click OK
Delete the old database
Hope this work for all
Thank you
Ramesh Kumar

If the above doesn't work, find the loginname of the spid and disable it in Security - Logins

I have solved the problem easily
Right click on database name rename it
After changing, right click on database name --> properties --> options --> go to bottom of scrolling RestrictAccess (SINGLE_USER to MULTI_USER)
Now again you can rename database as your old name.

On more than 3 occasions working with SQL Server 2014, I have had a database convert to Single User mode without me changing anything. It must have occurred during database creation somehow. All of the methods above never worked as I always received an error that the database was in single user mode and could not be connected to.
The only thing I got to work was restarting the SQL Server Windows Service. That allowed me to connect to the database and make the necessary changes or to delete the database and start over.

just go to database properties
and change SINGLE USER mode to MULTI USER
NOTE:
if its not work for you then take Db backup and restore again and do above method again
*
Single=SINGLE_USER
Multiple=MULTI_USER
Restricted=RESTRICTED_USER

After going in to the Single-User mode, a client can establish only ONE connection with the SQL Server, remember that "Object Explorer" takes up a (separate) connection, so if you are trying run a Multi-User statement in a query window, you will get error that in Single-User mode you can't establish another connection.
For me this wasn't the issue though, in my case, there were few automated processes that were persistently (in every few seconds) establishing connections, so as soon as I took the DB into Single-User mode and disconnected myself, one of the processes established/occupied the connection (before I could start my Restore operation). As soon as I'd kill those connections - they'd reconnect and when I ran the Restore command, I would get the error that connection is already occupied.
To resolve this I had to write the kill statements, change of User-Mode statements and Restore operations all in one query window and when I ran them all in one go, voila!!! it worked.
Hope this helps others.

I was having trouble with a local DB.
I was able to solve this problem by stopping SQL server, and then starting SQL server, and then using the SSMS UI to change the DB properties to Multi_User.
The DB went into "Single User" Mode when i was attempting to restore a backup. I hadn't created a backup of the target database before attempting to restore (SQL 2017). this will get you every time.
Stop SQL Server, Start SQL Server, then run the above Scripts or use the UI.

I googled for the solution for a while and finally came up with the below solution,
SSMS in general uses several connections to the database behind the scenes.
You will need to kill these connections before changing the access mode.(I have done it with EXEC(#kill); in the code template below.)
Then,
Run the following SQL to set the database in MULTI_USER mode.
USE master
GO
DECLARE #kill varchar(max) = '';
SELECT #kill = #kill + 'KILL ' + CONVERT(varchar(10), spid) + '; '
FROM master..sysprocesses
WHERE spid > 50 AND dbid = DB_ID('<Your_DB_Name>')
EXEC(#kill);
GO
SET DEADLOCK_PRIORITY HIGH
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO
To switch back to Single User mode, you can use:
ALTER DATABASE [<Your_DB_Name>] SET SINGLE_USER
This should work. Happy coding!!
Thanks!!

What I do:
First I kill all database process, to certificate that database isn't in use.
After I alter the user mode.
Sometimes a process is quickly grabed again from an aplication, and I need run this process one more time...
Replace the expression DATABASE_NAME below, to use your database name.
--Kill process
USE Master
GO
declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid = db_id('DATABASE_NAME') and spid != ##spid
while (#spid is not null)
begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
spid > 50 AND dbid = db_id('DATABASE_NAME')
and spid != ##spid
end
print 'Killing Process completed...'
GO
**--Alter user mode**
ALTER DATABASE DATABASE_NAME SET MULTI_USER;
GO
print 'Alter Database Process completed...'

Related

SQL deadlocking..in single user mode now

Couple of databases produced an error this morning whilst running in Single User Mode. Due to the following error I am unable to do anything :(
Msg 1205, Level 13, State 68, Line 1
Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
I receive that error when trying the following (using the Master Database as a Sys Admin):
ALTER DATABASE dbname
SET MULTI_USER;
GO
For the sake of it I have tried Restarting the SQL Server, I have tried killing any processes and I have even tried resetting the single user myself:
ALTER DATABASE dbname
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
The job which was running was designed to copy the database and put it in single user mode immediately to try and make it faster.
Anyway I can remove the locks?
Had the same problem. This worked for me:
set deadlock_priority high; -- could also try "10" instead of "high" (5)
alter database dbname set multi_user; -- can also add "with rollback immediate"
From ideas/explanation:
http://myadventuresincoding.wordpress.com/2014/03/06...
http://www.sqlservercentral.com/blogs/pearlknows/2014/04/07/...
Ok, I will answer my own.
I had to use the following:
sp_who
which displayed details of the current connected users and sessions, I then remembered about Activity Monitor which shows the same sort of stuff...Anyway that led me away from my desk to some bugger who had maintained connections to the database against my wishes...
Anyway once I had shut the PC down (by unplugging it...deserved it) I could then run the SQL to amend it into MULTI_USER mode (using system admin user):
USE Master
GO
ALTER DATABASE dbname
SET MULTI_USER;
GO
FYI for those who care, this can be used to immediately set the DB to SINGLE_USER:
ALTER DATABASE dbname
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
Further details, if you know the process id you can use kill pid:
kill 62
Bare in mind SSMS creates a process for your user as well, in my case this was being rejected due to another.
EDIT: As Per Bobby's recommendations we can use:
sp_Who2
This can show us which process is blocked by the other process.
tanks a lot.
SET DEADLOCK_PRIORITY HIGH ---- could also try "10" instead of "high" (5)
GO
ALTER DATABASE SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE SET MULTI_USER
GO
When related system processes are at dead block scenario.
SPID 15 & SPID 29 - both are background SysProcesses.
This helps in such cases:
--------- START OF CMDs--------
SET DEADLOCK_PRIORITY HIGH ---- could also try "10" instead of "high" (5)
GO
ALTER DATABASE <dbname> SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE <dbname> SET MULTI_USER
GO
-------------------------- END OF CMDs ------------------
Blocking Case with an User DB RESTORE process putting DB in Single_User

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I am actually trying to make a script (in Sql Server 2008) to restore one database from one backup file. I made the following code and I am getting an error -
Msg 3101, Level 16, State 1, Line 3
Exclusive access could not be obtained because
the database is in use.
Msg 3013, Level 16, State 1, Line 3
RESTORE DATABASE is terminating abnormally.
How do I fix this problem ?
IF DB_ID('AdventureWorksDW') IS NOT NULL
BEGIN
RESTORE DATABASE [AdventureWorksDW]
FILE = N'AdventureWorksDW_Data'
FROM
DISK = N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\Backup\AdventureWorksDW.bak'
WITH FILE = 1,
MOVE N'AdventureWorksDW_Data'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW.mdf',
MOVE N'AdventureWorksDW_Log'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW_0.LDF',
NOUNLOAD, STATS = 10
END
Set the path to restore the file.
Click "Options" on the left hand side.
Uncheck "Take tail-log backup before restoring"
Tick the check box - "Close existing connections to destination database".
Click OK.
I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO
Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.
execute this query before restoring database:
alter database [YourDBName]
set offline with rollback immediate
and this one after restoring:
alter database [YourDBName]
set online
For me, the solution is:
Check Overwrite the existing database(WITH REPLACE) in optoins tab at left hand side.
Uncheck all other options.
Select source and destination database.
Click ok.
That's it.
taking original db to offline worked for me
Use the following script to find and kill all the opened connections to the database before restoring database.
declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid = db_id('<database_name>')
and spid != ##spid
while (#spid is not null)
begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
dbid = db_id('<database_name>')
and spid != ##spid
end
print 'Process completed...'
Hope this will help...
I just restarted the sqlexpress service and then the restore completed fine
I think you just need to set the db to single user mode before attempting to restore, like below, just make sure you're using master
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
Use Master
alter database databasename set offline with rollback immediate;
--Do Actual Restore
RESTORE DATABASE databasename
FROM DISK = 'path of bak file'
WITH MOVE 'datafile_data' TO 'D:\newDATA\data.mdf',
MOVE 'logfile_Log' TO 'D:\newDATA\DATA_log.ldf',replace
alter database databasename set online with rollback immediate;
GO
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.
Be sure to check the 'Drop All Active Connections' option in the dialog.
Vinu M Shankar's solution worked for me.
But I had to check the: "Take tail-log backup before restoring" checkbox for mine to work.
Here's a way I am doing database restore from production to development:
NOTE: I am doing it via SSAS job to push production database to development daily:
Step1: Delete previous day backup in development:
declare #sql varchar(1024);
set #sql = 'DEL C:\ProdAEandAEXdataBACKUP\AE11.bak'
exec master..xp_cmdshell #sql
Step2: Copy production database to development:
declare #cmdstring varchar(1000)
set #cmdstring = 'copy \\Share\SQLDBBackup\AE11.bak C:\ProdAEandAEXdataBACKUP'
exec master..xp_cmdshell #cmdstring
Step3: Restore by running .sql script
SQLCMD -E -S dev-erpdata1 -b -i "C:\ProdAEandAEXdataBACKUP\AE11_Restore.sql"
Code that is within AE11_Restore.sql file:
RESTORE DATABASE AE11
FROM DISK = N'C:\ProdAEandAEXdataBACKUP\AE11.bak'
WITH MOVE 'AE11' TO 'E:\SQL_DATA\AE11.mdf',
MOVE 'AE11_log' TO 'D:\SQL_LOGS\AE11.ldf',
RECOVERY;
I got this error when there was not enough disk space to restore Db. Cleaning some space solved it.
Solution 1 : Re-start SQL services and try to restore DB
Solution 2 : Re-start system / server and try to restore DB
Solution 3 : Take back of current DB, Delete the current/destination DB and try to restore DB.
I got this error when unbeknownst to me, someone else was connected to the database in another SSMS session. After I signed them out the restore completed successfully.
In my case although i tried all of the above solutions, the thing that worked, was to restart SSMS.

restore sql server from .bak file Exclusive access could not be obtained

I am trying to restore my sql using bak file
I am getting error
Exclusive access could not be obtained because the database is in use
I tried
USE [master]
ALTER DATABASE myDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
and run the query
USE [master] RESTORE DATABASE myDB
FROM DISK = 'C:\MyDatabase.bak' WITH FILE = 1, NOUNLOAD, STATS = 10
I also tried from restore wizard with same result.
Exclusive access could not be obtained because the database is in use.
Method 1
declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid = db_id('<database_name>') and spid != ##spid
while (#spid is not null)
begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
dbid = db_id('<database_name>')
and spid != ##spid
end
print 'Process completed...'
Method 2
alter database database_name
set offline with rollback immediate
alter database database_name
set online
go
Don't need to write any query to solve this problem.
I had the same problem several times and solve it by this method:
when you are restoring database
Go to Option tab in Restore database window
Check (Overwrite the existing database (WITH REPLACE))
Check (Close existing connections to destination database)
Then click OK
Restore database is starting...
Anyone that has had the issues listed above, and none of the advice works.. Just turn off the Taillog backup under 'options'..
Setting (or leaving) this option on will attempt to take a tail-log of the source database itself (even if your source for the restore is just a file). So if the source database is in use (which if you are doing a copy of a production DB will normally be the case) then the restore fails.
I had this issue when I was trying to restore a production backup to a dev server that already had the database there. I wanted to restore as a copy, which I did by changing the target database name, but the issue was actually with the files. By default, it was trying to overwrite the files that were already there. I fixed the issue by checking the "Relocate all files to folder" in the "Files" page of the restore dialog and choosing a new directory so there wouldn't be file collisions.
None of the above solution did not work for me.
After many trials and errors, I stopped SQL Server Browser and then the restore completed successfully

ALTER DATABASE failed because a lock could not be placed on database

I need to restart a database because some processes are not working. My plan is to take it offline and back online again.
I am trying to do this in Sql Server Management Studio 2008:
use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go
I am getting these errors:
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.
What am I doing wrong?
After you get the error, run
EXEC sp_who2
Look for the database in the list. It's possible that a connection was not terminated. If you find any connections to the database, run
KILL <SPID>
where <SPID> is the SPID for the sessions that are connected to the database.
Try your script after all connections to the database are removed.
Unfortunately, I don't have a reason why you're seeing the problem, but here is a link that shows that the problem has occurred elsewhere.
http://www.geakeit.co.uk/2010/12/11/sql-take-offline-fails-alter-database-failed-because-a-lock-could-not-error-5061/
I managed to reproduce this error by doing the following.
Connection 1 (leave running for a couple of minutes)
CREATE DATABASE TESTING123
GO
USE TESTING123;
SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6
Connections 2 and 3
set lock_timeout 5;
ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
Try this if it is "in transition" ...
http://learnmysql.blogspot.com/2012/05/database-is-in-transition-try-statement.html
USE master
GO
ALTER DATABASE <db_name>
SET OFFLINE WITH ROLLBACK IMMEDIATE
...
...
ALTER DATABASE <db_name> SET ONLINE
Just to add my two cents. I've put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has "only" limited permissions like:
ALTER ANY DATABASE
P.S. I've spent hours trying to figure out why the "ALTER DATABASE.." does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here's my MSDN thread!
I will add this here in case someone will be as lucky as me.
When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.
Check if you have any processes in KILL/RollBack state for master database
SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'
If you have the same issue, just the KILL command will probably not help.
You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.
In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.
In my case, I was logged in on an account without that privilege.
HTH!
Killing the process ID worked nicely for me.
When running "EXEC sp_who2" Command over a new query window... and filter the results for the "busy" database , Killing the processes with "KILL " command managed to do the trick. After that all worked again.
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.
In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.
To check if you still have processes running just execute this command:
select percent complete from sys.dm_exec_requests
where percent_complete > 0

Bulletproof way to DROP and CREATE a database under Continuous Integration

I am attempting to drop and recreate a database from my CI setup. But I'm finding it difficult to automate the dropping and creation of the database, which is to be expected given the complexities of the db being in use. Sometimes the process hangs, errors out with "db is currently in use" or just takes too long. I don't care if the db is in use, I want to kill it and create it again. Does some one have a straight shot method to do this? alternatively does anyone have experience dropping all objects in the db instead of dropping the db itself?
USE master
--Create a database
IF EXISTS(SELECT name FROM sys.databases
WHERE name = 'mydb')
BEGIN
ALTER DATABASE mydb
SET SINGLE_USER --or RESTRICTED_USER
--WITH ROLLBACK IMMEDIATE
DROP DATABASE uAbraham_MapSifterAuthority
END
CREATE DATABASE mydb;
We use Hudson to rebuild staging sites for our QA team all the time. We kill connections, drop the database, then restore/rebuild/remigrate a DB.
This is what I use to kill connections so I can drop a DB.
USE MASTER
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_KillDatabaseProcesses]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_KillDatabaseProcesses]
GO
CREATE PROCEDURE dbo.sp_KillDatabaseProcesses(#databaseName varchar(100))
AS
DECLARE #databaseId int,
#sysProcessId int,
#cmd varchar(1000)
EXEC ('USE MASTER')
SELECT #databaseId = dbid FROM master..sysdatabases
WHERE [name] = #databaseName
DECLARE sysProcessIdCursor CURSOR FOR
SELECT spid FROM [master]..[sysprocesses] WHERE [dbid] = #databaseId
OPEN sysProcessIdCursor
FETCH NEXT FROM sysProcessIdCursor INTO #sysProcessId WHILE ##fetch_status = 0
BEGIN
SET #cmd = 'KILL '+ convert(nvarchar(30),#sysProcessId)
PRINT #cmd
EXEC(#cmd)
FETCH NEXT FROM sysProcessIdCursor INTO #sysProcessId
END
DEALLOCATE sysProcessIdCursor
GO
Setting single user with rollback immediate is the typical way of kicking everyone out before a drop.
But I'm a bit surprised that your CI drops the DB and creates it in the same script. Normally the CI should deploy the database, using the deploy script/methods of your build deliverable, just as a customer would do it. But you can't seriously have a deployment script that drops the database on the customer deployment. Usually the CI has a step to cleanup/flatten the test server, and then run the build deliverable setup process, which will deploy the database. And you should also have a story for upgrade scenarios, perhaps using an application metadata version upgrade step.