Extreme wait-time when taking a SQL Server database offline - database

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 .

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: Restoring DB via linked server - Database intermittently stuck in restoring state (even with RECOVERY option)

I am doing restores across servers via dynamic sql and linked servers as follows:
Exec ('USE MASTER; RESTORE DATABASE <dbname> FROM DISK = <path> WITH REPLACE, RECOVERY') AT <target server>
The database is set to single user mode before the above statement runs. However, on intermittent occasions, when trying to get the database back to multi user mode I get the a query timeout from the the target server and error:
ALTER DATABASE is not permitted while a database is in the Restoring state
I have looked around for this error but apparently I'm should not be getting it when using the RECOVERY option.
Any ideas please?
I managed to figure this out today. The culprit behind the issue was the default remote query time out for Sql Server which is 600s (10mins). More on this in the following link https://msdn.microsoft.com/en-us/library/ms189040(v=sql.105).aspx
My restore usually takes around 10mins to complete, sometimes a bit less so it succeeds and sometimes a bit more when it fails. Hence the issue was manifesting itself intermittently.
I increased the remote query time out on the source server to 36000s and it restored successfully. Just to prove the point, I decreased the remote query time out to a small figure like 60s and got the same symptom again.
Michelle - I set the database in single user to kill any running queries before the restore and to make sure there are no conflicts whilst the database is restored. This would eliminate the Exclusive Access could not be obtained because the database is in use error. Alternatively the database can be put to offline before the restore is initiated and back to online afterwards.

Why does SQL Server say "Starting Up Database" in the event log, twice per second?

I have a SQL Server [2012 Express with Advanced Services] database, with not much in it. I'm developing an application using EF Code First, and since my model is still in a state of flux, the database is getting dropped and re-created several times per day.
This morning, my application failed to connect to the database the first time I ran it. On investigation, it seems that the database is in "Recovery Pending" mode.
Looking in the event log, I can see that SQL Server has logged:
Starting up database (my database)
...roughly twice per second all night long. (The event log filled up, so I can't see beyond yesterday evening).
Those "information" log entries stop at about 6am this morning, and are immediately followed by an "error" log entry saying:
There is insufficient memory in resource pool 'internal' to run this query
What the heck happened to my database?
Note: it's just possible that I left my web application running in "debug" mode overnight - although without anyone "driving" it I can't imagine that there would be much database traffic, if any.
It's also worth mentioning that I have a full-text catalog in the database (though as I say, there's hardly any actual content in the DB at present).
I have to say, this is worrying - I would not be happy if this were to happen to my production database!
With AUTO_CLOSE ON the database will be closed as soon as there are no connections to it, and re-open (run recovery, albeit a fast paced one) every time a connection is established to it. So you were seeing the message because every 2 second your application would connect to the database. You probably always had this behavior and never noticed before. Now that your database crashed, you investigated the log and discovered this problem. While is good that now you know and will likely fix it, this does not address you real problem, namely the availability of the database.
So now you have a database that won't come out of recovery, what do you do? You restore from you last backup and apply your disaster recovery plan. Really, that's all there is to it. And there is no alternative.
If you want to understand why the crash happened (it can be any of about 1 myriad reasons...) then you need to contact CSS (Product Support). They have the means to guide you through investigation.
If you wanted to turn off this message in event log.
Just goto SQL Server Management Studio,
Right click on your database
Select Options (from left panel)
Look into "Automatic" section, and change "Auto Close" to "False"
Click okay
That's All :)
I had a similar problem with a sql express database stuck in recovery. After investigating the log it transpired that the database was starting up every couple of minutes. Running the script
select name, state_desc, is_auto_close_on from sys.databases where name = 'mydb'
revealed that auto close was set to on.
So it appears that the database is in always in recovery but is actually coming online for a brief second before going offline again because there are no client connections.
I solved this with following script.
Declare #state varchar(20)
while 1=1
begin
Select #state = state_desc from sys.databases where name='mydb';
If #state = 'ONLINE'
Begin
Alter database MyDb
Set AUTO_CLOSE_OFF;
Print 'Online'
break;
End
waitfor delay '00:00:02'
end

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.

Drop all active database connections failed for Server when executing KillAllProcesses

I need to perform a database restore from my application. Before doing this, I want to kill all processes as follows:
private void KillAllProcessesOnSMARTDatabases(Server targetServer)
{
targetServer.KillAllProcesses(SMART_DB);
targetServer.KillAllProcesses(SMART_HISTORY_DB);
targetServer.KillAllProcesses(SMART_METADATA_DB);
SqlConnection.ClearAllPools();
}
However, when the first KillAllProcesses is run, I get the following exception:
Microsoft.SqlServer.Management.Smo.FailedOperationException: Drop all active database connections failed for Server 'MYServer'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Only user processes can be killed.
The connection string used to create the server has sa credentials, however, the processes that need to be terminated are started under a different user. I tested the similar scenario and the test succeeded.
This started happening only recently. To me it appears there are some processes running that are not started by the user?
It would appear that your code is attempting to terminate all SQL Server Processes, which is not a good idea.
If you want to perform a database restore, you should set the database in question into either single_user mode or RESTRICTED_USER mode, the later being the most suitable.
Take a look at the following example of switching a database to RESTRICTED_USER mode and how to close any open user connections in the process.
How to: Set a Database to Single-User mode
You can use SMO to "kill" a particular database.
This will force a drop of all client connections to that database only and then drop the database itself.
Microsoft.SqlServer.Management.Smo.Server oServer = this.GetSmoServer();
oServer.KillDatabase(this.DatabaseName);

Resources