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

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

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

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

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.

When restoring a backup, how do I disconnect all active connections?

My SQL Server 2005 doesn't restore a backup because of active connections. How can I force it?
You want to set your db to single user mode, do the restore, then set it back to multiuser:
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK AFTER 60 --this will give your current connections 60 seconds to complete
--Do Actual Restore
RESTORE DATABASE YourDB
FROM DISK = 'D:\BackUp\YourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf'
/*If there is no error in statement before database will be in multiuser
mode. If error occurs please execute following command it will convert
database in multi user.*/
ALTER DATABASE YourDB SET MULTI_USER
GO
Reference : Pinal Dave (http://blog.SQLAuthority.com)
Official reference: https://msdn.microsoft.com/en-us/library/ms345598.aspx
SQL Server Management Studio 2005
When you right click on a database and click Tasks and then click Detach Database, it brings up a dialog with the active connections.
By clicking on the hyperlink under "Messages" you can kill the active connections.
You can then kill those connections without detaching the database.
More information here.
SQL Server Management Studio 2008
The interface has changed for SQL Server Management studio 2008, here are the steps (via: Tim Leung)
Right-click the server in Object Explorer and select 'Activity Monitor'.
When this opens, expand the Processes group.
Now use the drop-down to filter the results by database name.
Kill off the server connections by selecting the right-click 'Kill Process' option.
This code worked for me, it kills all existing connections of a database.
All you have to do is change the line Set #dbname = 'databaseName' so it has your database name.
Use Master
Go
Declare #dbname sysname
Set #dbname = 'databaseName'
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
after this I was able to restore it
Try this:
DECLARE UserCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
spid
FROM
master.dbo.sysprocesses
WHERE DB_NAME(dbid) = 'dbname'--replace the dbname with your database
DECLARE #spid SMALLINT
DECLARE #SQLCommand VARCHAR(300)
OPEN UserCursor
FETCH NEXT FROM UserCursor INTO
#spid
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQLCommand = 'KILL ' + CAST(#spid AS VARCHAR)
EXECUTE(#SQLCommand)
FETCH NEXT FROM UserCursor INTO
#spid
END
CLOSE UserCursor
DEALLOCATE UserCursor
GO
Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.
But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works
Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.
I ran across this problem while automating a restore proccess in SQL Server 2008.
My (successfull) approach was a mix of two of the answers provided.
First, I run across all the connections of said database, and kill them.
DECLARE #SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While #spid Is Not Null
Begin
Execute ('Kill ' + #spid)
Select #spid = top 1 spid from master.dbo.sysprocesses
where dbid = db_id('dbName')
End
Then, I set the database to a single_user mode
ALTER DATABASE dbName SET SINGLE_USER
Then, I run the restore...
RESTORE DATABASE and whatnot
Kill the connections again
(same query as above)
And set the database back to multi_user.
ALTER DATABASE dbName SET MULTI_USER
This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.
None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.
To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database
None of the above worked for me. My database didn't show any active connections using Activity Monitor or sp_who. I ultimately had to:
Right click the database node
Select "Detach..."
Check the "Drop Connections" box
Reattach
Not the most elegant solution but it works and it doesn't require restarting SQL Server (not an option for me, since the DB server hosted a bunch of other databases)
I prefer to do like this,
alter database set offline with rollback immediate
and then restore your database.
after that,
alter database set online with rollback immediate

Resources