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

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

Related

Troubleshoot a Full Transaction Log (SQL Server Error 9002)

we have quite a bit of automataion which runs at scheduled times, however I do not manage this and the person who does is on annual leave. Of course it's all fallen over
Usually the go to fix is to update the tbl_Control which contains columns to advise whether any of the automation is already running and delete the running field. One job started but has failed and I'm unable to clear the running field on the tbl_Control and that is where all the automation falls over providing variations of the message below.
Using:
SELECT log_reuse_wait_desc, name, database_id, state, state_desc
FROM sys.databases
It states the database (for which the transaction log is full)
log_reuse_wait_desc ACTIVE_TRANSACTION
So I think I need to stop that running and start again but as I can't update the tbl_Control I'm stuck.
Now I think I might have to do something in SQL to the database (maybe to clear the Transaction Logs, or make space?) but I have no idea
Thanks
You have to backup transaction log. You can also extend the size of the transaction log if it has fixed size. The last thing you can do is to check the disk space on the partition where your transaction log is stored and free some space. But backup transaction log should be first.
Backup Transaction log:
Connect with SSMS to your server.
Select your database under Server Name->Databases->[Your database name] and right click on it.
Choose 'Tasks'->'Back Up...'
On page 'General' select 'Transaction Log' as 'Backup type'
On page 'General' select 'Disk' as 'Back up to'
On page 'General' add new destination clicking 'Add..' button
Click [OK].
Notify administrator about backup you did.

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.

SQL Management Studio 2008 R2 "wrongly" reconnects after connection loss

up to a while ago I used SQL2k5 exclusively but recently got updated to 2008 R2. Apart from the obvious changes in Mgmt Studio, there is one quirk that's starting to be very annoying : each time a connection is dropped, I have to switch back to the 'lost' database again as it seems the conneciton automagically reconnected to the initial database again.
In SQL 2005 I simply had to press F5 twice and the first time it would give me an error saying the connection was lost, the second time it would reconnect to the database it was on before the connection got dropped and then execute whatever sql-commands it had. It did not really matter how I had gotten to that database, be it by using the dropdown-box on top, or a USE statement...
In SQL 2008 (R2) I now press F5 and mgmt studio will "eat" the lost connection silently and instead immediately reconnect to the server and execute the code on the default database or the database that I 'forced' while connecting using the [>> options] button/tabs
This happens quite a lot as I often have one tab open that kills all connections and restores the database, and another (series of) tab(s) with changed procedures, test-cases etc...
Is there some (hidden) configuration to (re)set this behaviour ???
I know I can try to add USE statements on top everywhere, or 'force' every connection directly to it's 'target' database, but bye bye for ad-hoc queries then =(
ps : doing some extra searching I'm wondering if this isn't due to the "fix" bespoken
here [connect.com]
ps: as a side note, after reconnecting the SPID on the bottom of the screen isn't updated properly either, as a result I've already been killing the wrong connection as I based myself on stale information ... yay for progress =( (**)
Anyone with better google-fu than me ? Or closer connections to Microsoft ? =)
Thx.
(**: man, I so miss Query Analyzer =)
If you register the instance you're connecting to in management studio, you can go to "Connection Properties" on the registered instance and set "Connect to database" to be the main database you use on that instance. When you are disconnected and it auto-reconnects, it will use that default database again.
Limitations:
You can only set this to one database per instance, by design.
You need to connect using that registered instance to get it to work (right click on it, then 'New Query'). If you just do a new connection without going to the Registered Servers pane, it won't apply the properties to the connection.
Certainly not a perfect solution, but perhaps better than nothing.
PS: Connect bug for incorrect spid is here. It looks like there is a promised fix in Denali
Note: rereading, I see you're already setting the database on the advanced options for your connection at times. This is no more helpful than that, of course, just prevents you from having to do it each time.

Determine which user deleted a SQL Server database?

I have a SQL Server 2005 database that has been deleted, and I need to discover who deleted it. Is there a way of obtaining this user name?
Thanks, MagicAndi.
If there has been little or no activity since the deletion, then the out-of-the-box trace may be of help. Try running:
DECLARE #path varchar(256)
SELECT #path = path
FROM sys.traces
where id = 1
SELECT *
FROM fn_trace_gettable(#path, 1)
[In addition to the out-of-the-box trace, there is also the less well-known 'black box' trace, which is useful for diagnosing intermittent server crashes. This post, SQL Server’s Built-in Traces, shows you how to configure it.]
I would first ask everyone who has admin access to the Sql Server if they deleted it.
The best way to retrieve the information is to restore the latest backup.
Now to discuss how to avoid such problems in the future.
First make sure your backup process is running correctly and frequently. Make transaction log baclup evey 15 mintues or half an hour if it is a higly transactional database. Then the most you lose is a half an hour's worht of work. Practice restoring the database until you can easily do it under stress.
In SQL Server 2008 you can add DDL triggers (not sure if you can do this in 2005) which allow you to log who did changes to structure. It might be worth your time to look into this.
Do NOT allow more than two people admin access to your production database - a dba and a backup person for when the dba is out. These people should load all changes to the database structure and code and all of the changes should be scripted out, code reviewed and tested first on QA. No unscripted, "run by the seat of your pants" code should ever be run on prod.
Here is bit more precise TSQL
SELECT DatabaseID,NTUserName,HostName,LoginName,StartTime
FROM
sys.fn_trace_gettable(CONVERT(VARCHAR(150),
( SELECT TOP 1
f.[value]
FROM sys.fn_trace_getinfo(NULL) f
WHERE f.property = 2
)), DEFAULT) T
JOIN sys.trace_events TE ON T.EventClass = TE.trace_event_id
WHERE TE.trace_event_id =47 AND T.DatabaseName = 'delete'
-- 47 Represents event for deleting objects.
This can be used in the both events of knowing or not knowing the database/object name. Results look like this:

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 .

Resources