SqlServer restore database error - sql-server

I'm using SQL Server 2008 R2, I need to restore a database from a .bak file. There is always an error that the database is in use until I restart the SQL Server service.
Is there a better option to do that?

Use this code to destory all existing connections before restore:
USE master;
GO
ALTER DATABASE YourDB
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
ALTER DATABASE YourDB
SET MULTI_USER;
GO

Select the backup file to restore and go to options to select "Close existing connections to destination database" and click ok

Restarting the SQL Service solves my problems.

The problem is that your database is currently being used by others and probably has open connections. What you would need to do is close all the existing connections to it, and then restore your backup.
Here is a link showing how to kill active connections: http://wiki.lessthandot.com/index.php/Kill_All_Active_Connections_To_A_Database

USe activity monitor and filter on the DB you are wanting to restore. Then check with the user that is using it and make sure it is ok to resotre the DB. Then run the following query.
USE Master
KILL <session_id from activity monitor>

Shut down the database engine and start it again. Do not just restart because it doesn't stop the instance completely. The error may be fake but check your environment to confirm there are no running applications that automatically reconnect after losing a database connection.
I have never found an answer to explain why restoring from a file to a new database is considered "in use".
Sometimes, #Serjik's answer to take the origin database down to single-user and back has worked for me. About 80% of the time, I have to shut it all down and start it up again before I can restore through SQL Server Management Server.

If still not solved try to execute following
Restore database YOUR_DB_NAME with recovery

What worked for me was:
right click on your db -> Tasks -> Take Offline
restore db
then, to bring it back online, right click on your db -> Tasks -> Bring Online

try restoring using SQL
RESTORE DATABASE my_new_database FROM disk = 'E:\path\name.bak'
sometimes I had these issues with UI but worked fine with SQL statement.
you need to kill all the open process before restoring, sometimes the process can not close themselves due to some issues with your windows or SQL installation files.

Related

How to fix Recovery Pending State in SQL Server Database?

How to fix Recovery Pending State in SQL Server Database?
Execute the following set of queries:
ALTER DATABASE [DBName] SET EMERGENCY;
GO
ALTER DATABASE [DBName] set single_user
GO
DBCC CHECKDB ([DBName], REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
GO
ALTER DATABASE [DBName] set multi_user
GO
For more info: https://www.stellarinfo.com/blog/fix-sql-database-recovery-pending-state-issue/
When your Database .mdf file name is renamed, this issue is occurred. To solve:
Restart SQL EXPRESS in Services, Pending issue is solved.
In our case it was caused by the disk drive running out of space. We deleted some junk to free space, then fixed the "Recovery Pending" by stopping and restarting the SQL Server Service.
Detach, re-attach, solved !
ALTER DATABASE MyDatabase SET EMERGENCY;
EXEC sp_detach_db MyDatabase
EXEC sp_attach_single_file_db #DBName = MyDatabase, #physname = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyDatabase.mdf'
While using SQL Management Studio, there is an intermittent issue when a user is changing the Database Names then sometimes SQL Server uses the same DB file for two different Databases. If SQL Server is in this state then you would be probably seeing the following error if you try Mahesh's answer:
"The process cannot access the file because it is being used by another process"
To fix this issue:
Stop MSSQLServer service from the Services Console MMC
Rename the DB and the Log files (Database Properties -> Files)
In the Object Explorer window in SQL Management Studio, refresh the 'Databases Folder', if you see that there is another Database node (in addition to the one which you are trying to rectify this issue) which is shown in 'Recovery Pending State' then proceed to the next step. If you do not see this error then you need to try something else to resolve this issue
Make a backup of the DB and Log files for new offending node from step 3 and !!Careful!! delete the database
Restore the Db File names which you changed in Step 2
Now start the MSSQLServer service from the Services Console
Re-try the steps from Mahesh's answer
In my case, this affected the secondary server in a High Availability SQL Server cluster.
The primary was Synchronizing but the secondary was Recovery Pending.
After checking in cluadmin.msc, realised that the secondary server wasn't healthy in the cluster.
Then determined Cluster Service had failed to start on the second cluster box after a Windows Update enforced reboot (may have happened because the file share witness was rebooting after a similar Windows Update at the same time).
Starting the Cluster Service brought the databases back into Synchronizing status.
Ensure that the "Log On" account for the "SQL Server (201x)" service (listed in Windows Services (Manager)) has sufficient rights. You may try changing it to another Logon. In my case, changing it from "This account" to "Local System account", restarting the "SQL Server (xxxx)" service and SQL Server Management Studio (SSMS), and logging into SSMS again resolved the issue.
Background (in my particular case):
I had 3 different instances of SQL (2008r2, 2012 and 2014) running on my local PC, and was busy moving a folder (which I later discovered contained some SQL data & log database files) to another PC. Halfway through, I stopped the SQL Services in Service (Manager), hoping that the files would move across without issues - since they would now, no longer be in use. I realized that I needed to confirm the database names, and file locations in SQL (in order to set them up again on the new pc), so I copied the SQL data and log files back (to the original locations). After restarting the PC - the majority of the databases on various instances all showed as: "Recovery Pending" in SSMS. After first trying the procedure from stellarinfo (listed as an answer here by #Mahesh Thorat) on 2 of the databases, and still not having any luck, a post SQL SERVER – Where is ERRORLOG? Various Ways to Find ERRORLOG Location on Pinal Dave's SQL Authority website and the post: Operating System error 5(Access is Denied) on SQL Server Central gave me an idea that it could be rights related after looking at the SQL Errorlog and finding "Operating system error 5: "5(Access is denied.)". Another post Msg 3201, Level 16 Cannot open backup device. Operating system error 5(Access is denied.) at SqlBak Blog seems to support this.
I was using azure, the mdf and log file are in different disk and not attached that disk with which it is not able to figure that files and hence the file Recovery Pending
This could happen due to insufficient permissions for a folder with database files (in my case due to a domain migration).
Just give access to the folder for an SQL service's account.

SQL Server backup to Azure stopped working after moving DB files

I have a database in SQL Server 2014 on premises. For that database I have a backup to Azure storage configured using smart_admin.sp_set_db_backup procedure.
Recently I had to move the database files from one disk to another. I detached database, moved files, reattached it.
After that my backup stopped working. The function smart_admin.fn_backup_db_config shows that database backup record exists but database marked as is_dropped = 1
Any attempt to enable or disable backup for this database fails with error:
SQL Server Managed Backup to Windows Azure cannot configure the database, 'DATABASE_NAME', because it either does not exist or is offline.
Any way I can remove backup configuration information and create a new one? One of the ideas I found is rename the database, but I cannot do that in production.
Vad's answer is close, but there can be more than one record in autoadmin_managed_databases for a given db_name. You need to get the last record, which is the one with the max autoadmin_id. I picked the wrong one, and SQL Server repopulated the drop_date after I ran smart_admin.sp_set_db_backup or the 15 minute interval ran.
use msdb;
go
update [dbo].[autoadmin_managed_databases]
set drop_date = null
where [autoadmin_id]= (select max(autoadmin_id)
from [dbo].[autoadmin_managed_databases]
where db_name = '<DROPPPED_DATABASE_NAME>')
go
Managed Backups - is_dropped flag set to Yes after detaching database
and reattaching DB
Rename the database and set up managed backup again.
Reference
As I mentioned earlier I was not allowed to rename the database on the Production. So I found where it's marked as dropped and changed the value. That helped. Automated backups for the database started working again. IMO what happened looks like a bug in SQL Server 2014.
use msdb;
go
update [dbo].[autoadmin_managed_databases]
set drop_date = null
where [db_name] = '<DROPPED_DATABASE_NAME>'
go

How do I stop and start a SQL Azure database?

I am running an Azure based site that for historic reasons uses two databases on two servers. I have copied the data from the static data-source so that both reside on the same server. I am fairly sure I have removed all references to the old server from the live code, and indeed the Azure dashboard shows no connections over the last month. But to be 100% sure before I delete the server I would like to stop it and test the live site. If anything goes wrong I would then like to start it again. In SQL Server Management Studio this is usually straightforward, I can right-click on a server in the SQL Server Management Studio object explorer and select 'Stop' and then if needed 'Start'. However 'Stop' and 'Start' are not listed in the options for SQL Azure servers, nor is there anything I can see in the management pages on the Azure portal.
So my question is simple - how do I stop and start a SQL Azure database?
We had an issue with a Sql Azure db and were pretty sure it was in the server/service. We couldn't find the stop & start button, but did find a workaround:
Scale the database to another tier and then scale it back!
It solved our db issue.
Everybody says you don't need a stop/start button... but sometimes the theory differs from practice. Even Azure has issues :)
as Praggie mentioned, you cannot stop/start the SQL Azure servers. A SQL Azure Database resides on a shared host. there are other tenants on that server. you have access to the database, but not to the corresponding hosting server.
you can rename the database and if there's any app connecting to it, then they'd fail.
You can simply block the IPs (remove all the firewall rules, so that no one can connect)
A quick and dirty rename can work pretty good. Admin rights required!
USE master;
GO
ALTER DATABASE MyDatabaseIsAvailable
Modify Name = MyDatabaseIsNoMoreAvailable;
GO
do the opposite once you're done. The good thing is you can 'stop' a single Database when you have more than one on the same server
If this helps: in my situation, the database was locked. I could not alter tables, schema or anything else.
The way I found to handle this case was forcing read only and read write with rollback immediate.
ALTER DATABASE [MyDB]
SET READ_ONLY
WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [MyDB]
SET READ_WRITE
WITH ROLLBACK IMMEDIATE;
Warning, the top google result for "restart sql server database azure" gives one of the options for restarting as running DBCC STACKDUMP('Manual Failover – Reason: something').
Running that definitely causes something to happen, but in our case after 5 minutes the DTUs still weren't registering and the portal wasn't able to pull information on the size of the database.
After waiting 10 minutes for it to come back we ended up changing the tier and roughly 18 minutes later the tier change finished and the database was accessible again.

Trying to restore via t-sql script. Exclusive access could not be obtained because the database is in use

I'm trying to restore backups of our production databases to our development server. When I run the following script which has previously worked:
RESTORE DATABASE M2MDATA01 FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup' WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
I get the following error:
Error 12/21/2009 9:06:09 AM 0:00:00.000 SQL Server Database Error: Exclusive access could not be obtained because the database is in use. 5 0
However, I have no idea how what could possibly be using it. How can I tell?
Check what's connected (the easy way)
SELECT * FROM sys.sysprocesses S WHERE S.dbid = DB_ID('M2MDATA01')
Note: sysprocesses can not be emulated using dmvs...
Edit, check for locks too
SELECT * FROM sys.dm_tran_locks L WHERE L.resource_type = 'DATABASE' AND L.resource_database_id = DB_ID('M2MDATA01')
In SQL Server Management Studio, go to Management => Activity Monitor. This will show you all processes that are connected to all databases, and allow you to kill these processes (only recommended as a last resort).
Profiler is one option.
From Sql Server Management Studio, select Tools|Sql Server Profiler.
Connect to the server instance that the database you are working with is on.
Switch to the Event Selection tab
check the checkbox below the grid labeled "Show all columns"
In the grid find the DatabaseName column and check the entire column.
(optional) press the Column Filters button and filter to the database name you are working with.
This should at least tell you if something is using the database in question.
Easiest solution here is to delete the database and select the "close existing connections" checkbox before hitting okay. Then the restore will work just fine. It's just DEV right? :}
If you're restoring a db, do you really care who is connected? Or what is being done with those connections? I would think not. Just "kick everyone out" by setting the database into single user mode and then restore the database.
USER master
GO
ALTER DATABASE M2MDATA01
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE M2MDATA01
FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup'
WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
GO
Now, one additional item to be aware of. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once in a single batch.

How to recover database from MDF in SQL Server 2005?

I have an MDF file and no LDF files for a database created in MS SQL Server 2005. When I try to attach the MDF file to a different SQL Server, I get the following error message.
The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.
I would like to accomplish any one of the following options:
Attach the database without data loss (unlikely but would save me some time).
Attach the database with data loss (whatever transactions were open are lost).
Recover the schema only (no data) from the MDF file.
What SQL commands can I try to get my database going again?
I found the following document on Experts Exchange.
patrikt:
You will have data loss but it can be done.
1. Detach database and move your mdf to save location.
2. Create new databse of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY
7. ALTER DATABASE yourdb SET SINGLE_USER
8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER
10. ALTER DATABASE yourdb SET ONLINE
Here are details that cover parts 2) and 3) in case re-creating log doesn’t work which can happen if MDF file is corrupted.
You can recover data and structure only by reading MDF file with some third party tool that can de-code what’s written as binary data but even with such tools you can’t always do the job completely.
In such cases you can try ApexSQL Recover. From what I know this is the only tool that can do this kind of job but it’s quite expensive.
Much better idea is to try to recover these from any old backups if you have any.
FROM a post at SQL Server Forums Attaching MDF without LDF:
If you want to attach a MDF without LDF you can follow the steps below
It is tested and working fine
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the original MDF to this location and delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to update to Emergency mode. This will not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') -- Undocumented step to
create a new log file.
(replace the dbname and log file name based on ur requirement)
Execute sp_resetstatus
Restart SQL server and see the database is online.
UPDATE: DBCC REBUILD_LOG does not existing SQL2005 and above. This should work:
USE [master]
GO
CREATE DATABASE [Test] ON
(FILENAME = N'C:\MSSQL\Data\Test.mdf')
FOR ATTACH_REBUILD_LOG
GO
have you tried to ignore the ldf and just attach the mdf:
sp_attach_single_file_db [ #dbname = ] 'dbname' , [ #physname = ] 'physical_name'
i don't know exactly what will happen to your open transactions (probably just lost), but it might get your data back online.
-don
See here : Rebuild master and restore system databases from complete disk failure which has a very nice explanation
Just had this problem myself, but none of the above answers worked for me.
But instead, I found this which worked a treat and so I thought I'd share this for everyone else:
http://www.kodyaz.com/articles/sql-server-attach-database-mdf-file.aspx
Found a another way that works completely:
Create new database with same name to default database location.
Stop SQL server.
Copy old mdf file to overwrite newly created mdf file and delete new ldf file
Start SQL Server, database will be in emergency mode
Detach the emergency mode database
Copy original ldf file to default database location (where new LDF file as created and deleted under step 3 above.
Attach the database MDF file.
I got a working database after trying all of the above that failed for me.
I hope it is easy to do so,
Open SQL Server
Click New Query
Execute the following query
sp_attach_single_file_db #dbname='dbname',#physname='C:\Database\dbname.MDF'
Where dbname is you want to show in Object Explorer, where #physname is the local filepath location of your mdf file.
Hope it will help someone, i done by above, got both structure and also data.
Tested in Sql Server 2000 and 2008. In Sql Server 2000 it is not working, but works perfectly in 2008.

Resources