SQL Server tells me database is in use but it isn't - sql-server

SQL Server keeps telling me a database is in use when I try to drop it or restore it, but when I run this metadata query:
select * from sys.sysprocesses
where dbid
in (select database_id from sys.databases where name = 'NameOfDb')
It returns nothing.
Sometimes it will return 1 process which is a CHECKPOINT_QUEUE waittype. If I try to kill that process, it won't let me (cannot kill a non-user process).
Anyone have any idea what's wrong?

i like this script. Do not struggle with killing..
use master
alter database xyz set single_user with rollback immediate
restore database xyz ...
alter database xyz set multi_user

I was having the same issue when trying to restore a database from a backup. The solution for me was to ensure that I checked "Overrite the existing database(WITH REPLACE)" and "Close existing connections to destination database" in the Options page BEFORE doing the restore. Here is a screenshot below.

There could be lots of things blocking your database. For example, if you have a query window opened on that database, it would be locked by you. Not counting external accesses, like a web application on IIS.
If you really wanna force the drop on it, check the close existing connections option or try to manually stop SQL Server's service.

Related

How do I fix this 'Restore of database AdventureWorks2014 failed' permanently?

When I try to restore AdventureWorks2014, I get this
'Exclusive access could not be obtained because the database is in
use.(Microsoft.SqlServer.SmoExtended)'
Of course there is no query window open. I do not have this issue with other databases. The only difference that I found between AdventureWorks2014 and the rest of my databases is compatibility level, 2014 and 2019 respectively. But it was not the solution. I checked the Microsoft link provided with error message which took me to Microsoft home page. I could not find what I was looking for in Documentation. So I went around by setting the database offline or checking 'Close existing connections to destination database' option. Both of them works but I would like to find a permanent solution. Is there one?
Set the Database to SINGLE_USER before the RESTOE:
USE master
ALTER DATABASE AdventureWorks2014 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE AdventureWorks2014.....
Something was blocking your database restore. To find out what, issue the restore as T-SQL (even if you're going through some sort of UI, script it out so you can run it by hand) in one window and note the SPID for that window. If you don't know where to find that in your UI of choice (my guess is that you're using SSMS, but maybe not!), you can issue a query of SELECT ##SPID to find it. Before starting up your restore, open another window/session and get this query ready to run:
select *
from sys.dm_os_waiting_tasks
where session_id = «spid from your restore session»;
Kick off your restore and then run the above query to see what is blocking.

SQL Server Database Stuck Single User

I have a SQL Server 2016 on a Windows Server 2016.
The database is stuck in single user mode.
I try to do this :
ALTER DATABASE MyDatabase
SET MULTI_USER;
But it says that the database is in use.
I tried this to find the spID :
exec sp_who
And I found the spid 57 is using the database,
Tried this to kill the spID
KILL 57
But it says : Process ID 57 is not an active process ID.
I am really stuck!
I can't even rename or delete the database.
I tried all of these but, didn't work :
SQL Server 2008 R2 Stuck in Single User Mode
Any idea please ?
It means that the DB is in use, it's set to single user mode, and you're not that single user. A common cause of that is that Object Explorer in SSMS is connected to the DB. Close everything that's connected to the server (even restart the SQL Server service if you need to), and try again. At worst, don't use SSMS. Just connect with SQLCMD, so you know that nothing else is connected.
I found the solution,
I restarted the sql server service, re-execute the query exec sp_who and found another spID and could kill it this time.
Thanks
From the Official docs you can try changing it a little bit by removing the read-only part
ALTER DATABASE [database_name]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE [database_name]
SET MULTI_USER;
GO
Docs : https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-database-transact-sql-set-options?view=sql-server-ver15#b-setting-the-database-to-read_only

Database Keeps Going into Recovery Pending State

I have a SQL server database that has been running perfectly fine on my machine for about 6 months, a couple days ago out of nowhere it was inaccessible (Pending Recovery).
I did a bunch of Googling and have tried the following things to fix the issue but thus far restoring it from a previous backup is the only thing that seems to work.
I have tried (From SMS and SQLCMD):
ALTER DATABASE mydatabase SET EMERGENCY
ALTER DATABASE mydatabase set single_user
DBCC CHECKDB (mydatabase, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
ALTER DATABASE mydatabase set multi_user
Step #3 errors out with: "cannot open mydatabase is already open and can only have one user at a time"
Second try:
EXEC sp_resetstatus 'mydatabase';
ALTER DATABASE mydatabase SET EMERGENCY
DBCC CHECKDB ('mydatabase')
ALTER DATABASE mydatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CHECKDB ('mydatabase', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE mydatabase SET MULTI_USER
Step #5 errors out with the same error.
My question is what could be causing this in the first place and how can I fix it properly without having to do a restore twice a day.
Database is already open and can only have one user at a time, this is error number 924. The complete error message looks like this:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
Msg 924, Level 14, State 1, Line 1 Database ‘db_name’ is already open and can only have one user at a time.
The level 14 belongs to security level errors like a permission denied. It means that it cannot be open because someone is using it.
Use the sp_who or sp_who2 stored procedures. You can also use the kill command to kill the processes that are active in the database.
I also found this thread useful: How to fix Recovery Pending State in SQL Server Database?
what could be causing this in the first place and how can I fix it properly without having to do a restore
The most likely cause is a a hardware or driver problem with your hard disk.
In my case, I had databases set up on my local machine but on an external drive mapped to my hard drive. I have the external drive connected to my docking station all the time but I had to disconnect the hard drive and after I connected it again - the databases that are restored on the external drive went into Recover Pending mode.
In my case what helped me was to set the database offline in Microsoft SQL Server Management Studio by right clicking on the database - Tasks - Take Offline. The status of the database changes to Offline. After that bring the database online again by right clicking on the database - Tasks - Bring online.
The database was successfully recovered without any issues. But if the cause is different these steps may not help.
Take the database offline
Bring the database back online

Extreme wait-time when taking a SQL Server database offline

I'm trying to perform some offline maintenance (dev database restore from live backup) on my dev database, but the 'Take Offline' command via SQL Server Management Studio is performing extremely slowly - on the order of 30 minutes plus now. I am just about at my wits end and I can't seem to find any references online as to what might be causing the speed problem, or how to fix it.
Some sites have suggested that open connections to the database cause this slowdown, but the only application that uses this database is my dev machine's IIS instance, and the service is stopped - there are no more open connections.
What could be causing this slowdown, and what can I do to speed it up?
After some additional searching (new search terms inspired by gbn's answer and u07ch's comment on KMike's answer) I found this, which completed successfully in 2 seconds:
ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE
(Update)
When this still fails with the following error, you can fix it as inspired by this blog post:
ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.
you can run the following command to find out who is keeping a lock on your database:
EXEC sp_who2
And use whatever SPID you find in the following command:
KILL <SPID>
Then run the ALTER DATABASE command again. It should now work.
There is most likely a connection to the DB from somewhere (a rare example: asynchronous statistic update)
To find connections, use sys.sysprocesses
USE master
SELECT * FROM sys.sysprocesses WHERE dbid = DB_ID('MyDB')
To force disconnections, use ROLLBACK IMMEDIATE
USE master
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Do you have any open SQL Server Management Studio windows that are connected to this DB?
Put it in single user mode, and then try again.
In my case, after waiting so much for it to finish I had no patience and simply closed management studio. Before exiting, it showed the success message, db is offline. The files were available to rename.
execute the stored procedure
sp_who2
This will allow you to see if there is any blocking locks.. kill their should fix it.
In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.
In my case I had looked at some tables in the DB prior to executing this action. My user account was holding an active connection to this DB in SSMS. Once I disconnected from the server in SSMS (leaving the 'Take database offline' dialog box open) the operation succeeded.
anytime you run into this type of thing you should always think of your transaction log. The alter db statment with rollback immediate indicates this to be the case. Check this out: http://msdn.microsoft.com/en-us/library/ms189085.aspx
Bone up on checkpoints, etc. You need to decide if the transactions in your log are worth saving or not and then pick the mode to run your db in accordingly. There's really no reason for you to have to wait but also no reason for you to lose data either - you can have both.
Closing the instance of SSMS (SQL Service Manager) from which the request was made solved the problem for me.....
To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.
Also, close any query windows you may have open that are connected to the database in question ;)
I tried all the suggestions below and nothing worked.
EXEC sp_who
Kill < SPID >
ALTER DATABASE SET SINGLE_USER WITH Rollback Immediate
ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE
Result: Both the above commands were also stuck.
4 . Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Result: The window was stuck on executing.
As a last resort, I restarted the SQL server service from configuration manager and then ran ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE. It worked like a charm
In SSMS, set the database to read-only then back. The connections will be closed, which frees up the locks.
In my case there was a website that had open connections to the database. This method was easy enough:
Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Re-open Options and turn read-only back off
Now try renaming the database or taking it offline.
For me, I just had to go into the Job Activity Monitor and stop two things that were processing. Then it went offline immediately. In my case though I knew what those 2 processes were and that it was ok to stop them.
In my case, the database was related to an old Sharepoint install. Stopping and disabling related services in the server manager "unhung" the take offline action, which had been running for 40 minutes, and it completed immediately.
You may wish to check if any services are currently utilizing the database.
Next time, from the Take Offline dialog, remember to check the 'Drop All Active Connections' checkbox. I was also on SQL_EXPRESS on local machine with no connections, but this slowdown happened for me unless I checked that checkbox.
SSMS, especially if running it from your own desktop remotely and not directly within the database server, can be a reason for the long delays in detaching a database. For some reason SSMS may not be able to disconnect any existing "connections" to the database.
We found the process was almost instant when we did it directly from the database server itself. And in fact it killed the attempt from my own desktop SSMS session, and it "took over" and detached the database.
Nothing else suggested here worked.
Thanks
In my case i stopped Tomcat server . then immediately the DB went offline .

How to delete database, error 5030 database can't be locked

I am trying to delete an existing database in SQL Server 2005. My first attempt produced the following error:
5030: The database could not be exclusively
locked to perform the operation.
I have since killed all processes that are accessing the database. I have also removed the replication subscription that it had previously been involved in.
Any thoughts on what else that could be holding the lock on it besides SQL Server processes and replication?
Update: I restarted the server, and that fixed it. I was trying to avoid that, since this is a production server, but hey what can you do?
A production server in which so many connections use the database yet you want to drop it? :)
None the less, how to kick out everybody from the database:
USE [dbname];
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
Then drop the database:
USE [master];
DROP DATABASE [dbname];
There is still a very small window of opportunity between the USE [master]; and DROP DATABASE ... where some other connection can grab the 1 single allowed lock on the database, but it usually not worth working around that.
I hate to say it, but a quick solution is to restart the system, make sure the sql server server service is not started, then you should be able to delete.
Also, is IIS stopped if you db is connected to a web ap?
You don't happen to know if anyone left a transaction in an uncompleted rollback state (or otherwise uncompleted)? Might as well check the locks list, too.
In the management studio, goto Management->Activity Monitor (right click) -> View Processes. That will give you a full list of everything running, you can sort the list by Database to see what is still attached, and you can also kill any connections. It's easy to end up with orphaned connections that will prevent you from getting the exclusive access that you need.
No One else should be using the DB, including yourself.
Why would we make a deleted DB to multi user mode.
ALTER DATABASE dbName SET MULTI_USER WITH ROLLBACK IMMEDIATE
To avoid this error, use the T-SQL script below in the master database. Make sure to run this (and modify the #dbname) for each database you are running the ALTER DATABASE command in.
"The database could not be exclusively locked to perform the
operation"
This "connection killer" script will work if Windows has established JDBC connections to the database. But this script is unable to kill off JDBC connections for Linux services (e.g. JBoss). So you'll still get that error if you don't stop JBoss manually. I haven't tried other protocols, but please comment if you find out more information as you build new systems.
USE master;
DECLARE #dbname sysname
Set #dbname = 'DATABASE_NAME_HERE-PROD'
Declare #spid int
Select #spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(#dbname)
While #spid Is Not Null
Begin
Execute ('Kill ' + #spid)
Select #spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(#dbname) and spid > #spid
End
This error normally occurs when your database is in Multi User mode where users are accessing your database or some objects are referring to your database.
First you should set the database to single user mode:
ALTER DATABASE dbName
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Now we will try to delete the database
delete DATABASE ...
Finally set the database to Multiuser mode
ALTER DATABASE dbName
SET MULTI_USER WITH ROLLBACK IMMEDIATE

Resources