Query timeout until reset SQL Server - sql-server

Steps to reproduce (SQL Server 2008R2):
We restore a .bak file
We run the query (no other activity)
It times out
We restart sql server
We run the query
It runs really fast.
Reproduction rate 100%.
I've tried combinations of
DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS
DBCC FREESESSIONCACHE
DBCC FREESYSTEMCACHE ('ALL')
DBCC UPDATEUSAGE (dbname)
EXEC sp_updatestats
select * from master..sysprocesses where blocked <> 0
Nothing works, only restarting SQL Server.
I thought it would be just a bad plan, but expected FREEPROCCACHE to fix it, without restarting SQL Server. Is there some other cache I need to clear?
The query is not a transactional/blocking/locking style, mostly selects into and out of temporary tables it has created, and no other activities on the server.
I believe it must be a bad plan, but DBCC FREEPROCCACHE didn't do the job.
Does anyone have a clue?

Looks to me like you have an open connection to the database, yould be that you are "standing on your own feet". when you restore a database you need exclusive access so drop who is in the database und rollback any transaction that's going on (you restore is going to whype any thing that was dony anyway). Then you can restore your database.
Now a restart of SQL server will close all active connections however there is an easier way ;-)
USE MASTER;
GO;
ALTER DATABASE [YourDbName]-->change this to your database name
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
After that you can run your restore.
Have a nice day
Walter

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

Can I both finish restoring a DB backup and query that DB in the same stored procedure?

Here's my setup. Once a day, a full backup of my DB is retrieved from the production server and restored onto a local SQL Server instance. Every 15 minutes aftwerwards, a SQL transaction log is retrieved from production and restored locally.
RESTORE DATABASE [DBNAME] from disk=#path with NORECOVERY, REPLACE)
RESTORE LOG [DBNAME] from disk=#path with NORECOVERY
In case of a failure of the production environment, I need to be able to use the local DB instead. This means "finishing up the restore" and changing some configuration values like this :
RESTORE DATABASE [DBNAME] with RECOVERY
UPDATE [DBNAME].dbo.[TABLE] SET [COL1] = 1
I have put this code in a stored procedure (in another DB on the same SQL Server instance). However, I am unable to execute it as the second line causes an error:
Database 'DBNAME' cannot be opened. It is in the middle of a restore.
I assume this is due to pre-validation by the SQL Server engine (since the DB is not available until the RESTORE query is executed), but I would like to know how to work around it as cleanly as possible. I found a workaround, which I posted as an answer below, but it's definetely not a great way to solve the problem.
Thanks for the help!
You should be able to work around this by placing the second statement in an EXEC:
RESTORE DATABASE [DBNAME] with RECOVERY
EXEC('UPDATE [DBNAME].dbo.[TABLE] SET [COL1] = 1')
The issue you're likely seeing is that SQL Server wants to compile the entire stored procedure before it starts executing. In order to compile the UPDATE, it needs to, at the very least, confirm the existence of the table and column(s) involved.
So, put it in an EXEC so that it's not compiled until that part of the procedure is reached.
The workaround I have found is simple:
Create a stored procedure that executes the query on the database.
Call this SP in the first stored procedure.
However, I'd like to avoid cluttering up my SQL Server databases with unnecessary stored procedures if at all possible!
If you know roughly long it takes to restore you could put a delay in it maybe?
restore database [DBName] with recovery;
Begin
waitfor delay '00:01'; --one minute delay
update [DBTable] set [Col1]= 1;
END;

SQL Server 2008 db shrink error

I have SQL Server 2008 R2 Standard edition with 3 tb data. My disc is full. I want to shrink the .mdf file. I've deleted many rows from my db. And I launch
DBCC SHRINKDATABASE(my_db, TRUNCATEONLY)
I got error
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
I tried to do it in single user mode result is same. We have increased disk size to 4.5 tb and retried shrinking, result is same.
dbcc checkdb command shows no error on db.
Does anyone know what is problem?
Please help
Have you tried specifying both the file name and the target size in MB, e.g.
DBCC SHRINKFILE('filename', 20);
Or the TRUNCATEONLY option, which doesn't try any of the nasty stuff like reorganizing all of your physical data:
DBCC SHRINKFILE('filename', TRUNCATEONLY);
Also you could try making sure the database is in single user mode first:
ALTER DATABASE db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
...and turn off any backup / log backup or other maintenance jobs that may be conflicting with your shrink operation.

Resources