Restore database backup over the network - sql-server

How do you restore a database backup using SQL Server 2005 over the network? I recall doing this before but there was something odd about the way you had to do it.

You have few options to use a network file as a backup source
Map network drive/path, hosting file, under SAME user as MS-SQL Server.
Use xp_cmdshell extended stored procedure to map network drive from inside of MS SQL (such way, command shell will have the same privilegies as the user account running SSMS)
-- allow changes to advanced options
EXEC sp_configure 'show advanced options', 1
GO
-- Update currently configured values for advanced options.
RECONFIGURE
GO
-- To enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
-- Update currently configured values for advanced options.
RECONFIGURE
GO
EXEC xp_cmdshell 'NET USE Z: \\Srv\Path password1 /USER:Domain\UserName'
Afterwards drive Z: will be visible in Server Managment studio, or just
RESTORE DATABASE DataBaseNameHere FROM DISK = 'Z:\BackNameHere.BAK'
GO

The database is often running as a service under an account with no network access. If this is the case, then you wouldn't be able to restore directly over the network. Either the backup needs to be copied to the local machine or the database service needs to run as a user with the proper network access.

You cannot do this through the SSMS GUI, but you can do it using a script. RESTORE DATABASE from DISK='\unc\path\filename' If you need this process automated, the best way is to setup a SQL Server Job and run it as a user with access to the file location.

You can use the SP xp_cmdshell to map the networkdrive for sql server, after that it will show up in the file browsing window.
EXEC xp_cmdshell 'NET USE Z: SERVERLOCATION PASSWORD /USER:DOMAIN\USERNAME'
more info here: DB Restore from Network Drive
Worked for me!

Make sure that the user running your SQL services in "Services.msc" is an active directory "Domain User" this will fix the issue.

I've had to do this a few times, and there are only two options that I know of. Copy the file locally to the SQL Server, or on the SQL server create a mapped network drive to the share that contains the backup file.

Also, you need to make sure that the SQL Server Service is running as a user that has network access - and permissions to the share where the backup file lives. 'Local System' won't have permissions to access the network.

As a side note, if you happen to be running SQL on a Virtual Machine it's often less hassle to just temporarily set up a new drive on the VM with enough space to copy your backup files to, do the restore from that new local copy, and then delete the temp drive.
This can be useful if stopping/starting the SQL service to change it's account is an issue.

Create a shared drive on machine that has the backups, say server1 has the backups in folder "Backups". Grant full control to the account running the SQL Server. On the Server that you want to restore to launch SSMS go restore database and select "From Device". In the "Locate Backup file-"Server"" dialog box and remove anything in the "Selected Path" field and in the "File Name" field supply full path so "\server\backups\db.bak". At least it worked for me when migrating from 05 to 08. Not the preferred method because any network hiccup can cause an issue with the restore.

EXEC sp_configure 'show advanced options', 1
GO
-- Update currently configured values for advanced options.
RECONFIGURE
GO
-- To enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
-- Update currently configured values for advanced options.
RECONFIGURE
GO
--This should be run on command prompt (cmd)
NET USE Z: \\172.100.1.100\Shared Password /USER:administrator /Persistent:no
then on SQL Server
EXEC xp_cmdshell 'NET USE Z: \\172.100.1.100\Shared Password /USER:administrator /Persistent:no'
--Afterwards drive Z: will be visible in Server Management studio, or just
RESTORE DATABASE DB FROM DISK = 'Z:\DB.BAK'
WITH REPLACE

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.

Cannot open backup '' Operating system error 5(Access is denied.)

I am trying to restore a .bak file from one server to another server. Please see me syntax:
RESTORE DATABASE [NewDB]
FROM DISK = '\\aps-sql111\D$\MSSQL\Backup\OLDDB.bak'
WITH
MOVE 'OLDDB' TO 'M:\MSSQL\NewDB.mdf',
MOVE 'OLDDB_log' TO 'M:\MSSQL\NewDB.ldf',
REPLACE,
STATS=10
All I keep seeing is:
Cannot open backup device ''. Operating system error 5(Access is denied.).
Any help?
it looks like you are trying to restore over the network, accessing a bak file that is not local to the destination server: with the default sql configuration you cannot do that.
the default setup is to run the sql service as a local user (network service or local service, usually): a local user cannot access resources on remote machines.
there are at least 3 solutions:
copy the file locally in a folder accessible to the user used by the sql service
change the configuration of the sql service to run as a user that can access the backup folder over the network (i would not do that on a production system)
copy the bak file on a removeble storage to move the data from source to destination (or copy the bak on a SAN/NAS that can be mapped onto the destination server)
If we want to restore database using network share as described, we must perform few steps before the restore operation itself. The network share must be mapped as a network drive in the session in which SQL Server is running.
1. Map a Network drive in File Explorer
Open File Explorer
Select This PC from the left pane. Then, on the Computer tab, select Map network drive
In the Drive list, select a drive letter.
In the Folder box, type the path of the folder or computer, or select Browse to find the folder or computer. To connect every time you sign in to your PC, select Reconnect at sign-in.
Select Finish.
2. Map a Network drive in SQLServer
Please execute following commands in SQL Server Management Studio:
exec sp_configure 'show advanced options', 1 go reconfigure go
exec sp_configure 'xp_cmdshell',1 go reconfigure with override go
xp_cmdshell 'net use z: \\server_name\drive_name passwordhere /user:DOMAIN\USERNAME'
Now you should be able to see network drive from restore wizard.
Keep in mind, however, that this ability will be removed once we restart SQL server. So to prevent this we can create a stored procedure like below and make it a startup procedure for the SQL service. This way, all of the above is done for you every time SQL starts (such as machine reboots, etc.)
Map Network Share Permanently in SSMS
Create stored procedure
CREATE PROCEDURE [dbo].[mapdrives] AS exec xp_cmdshell 'net use z: \\server_name\drive_name passwordhere /user:DOMAIN\USERNAME' GO
Enable that stored procedure to run at startup:
exec sp_procoption 'mapdrives','startup','true'
Now we can reach network drive also using PowerShell.
One way is change log on type from Built-in-account to user account on SQL Server configuration and use an user with enough permission on network.
Open SQL Server configuration management
go to SQL Server Services
Chose SQL Server ([your instance name])
Right click on service and click properties
select tab Log On
Change to This account
Browse a user with access on network directory permission
Set user and password
Restart service
If you need working on JOB Backup set this user on SQL Server Agent Service.

Restoring database - Cannot access file because it is in use by another process

I have a backup of a database from another SQL Server 2005 machine. I'm attempting to restore it to my SQL Server 2008 instance.
I have created a new database for the restore to go in to, but when attempting the restore with the following (generated by ssms):
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
I get the following error:
System.Data.SqlClient.SqlError: The operating system returned the error '32 (The process cannot access the file because it is being used by another process.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'D:\databases\WendyUAT.mdf'.
As far as I can tell (using Process Explorer etc) nothing else is using the file. I've disabled real-time protection in windows defender. I just cannot understand why SQL Server thinks the file is in use as windows explorer lets me delete it with no problems so Windows doesn't seem to think it's in use.
Any help would be gratefully received.
How are you connecting to your SQL Server in your application before running this backup? What database are you connecting to?
You cannot connect to the WendyUAT database and use it when you want to restore it - you'll have to explicitly use some other database, e.g. master, before running your SMO restore code
All my T-SQL restore scripts will always include:
USE [master]
GO
RESTORE DATABASE [WendyUAT] ......
So if you run this backup from your app, make sure you explicitly connect to e.g. master before running this T-SQL restore script
Update:
Is this something you did on purpose, or might it just be a typo??
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
* **
* *
* * two backslashes here -why???
* only one backslash here...
Does it work if you use single backslashes only??
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
Try following script before restore
alter database DB_NAME set offline with rollback immediate;
and this script after restore to enable multi user
alter database DB_NAME set online with rollback immediate;
In my case I had installed two instances of SQL Server (2008 R2 and 2012). I had to stop one SQL Server service (2008 R2) from my two available SQL instances. This helped me to resolve this issue and I could restore my database.
I have the same issue.
What I did is that I just rename the Destination database to different name, then the restoration executed successfully. After the restoration, I just rename it to my desired database name.

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 does one move SQL Server error log files to a new location?

The default SQL Server log directory is full on my C drive. How does one move the SQL Server error log default directory?
Use the SQL Configuration Manager.
Here are the steps to change the startup to use a different directory. Once done restart server:
In SSMS go to server properties and look for start up parameters. Right-click in object explorer, properties, then advanced.
The path is the "e" switch. Change and restart.
It can't be set in documented SQL commands :-)
Basically, it's in the registry as one of the parameters to the sqlservr.exe binary when run as a windows service
When you use SSMS and click on generate script it creates T-SQL like this
USE [msdb]
GO
EXEC dbo.sp_set_sqlagent_properties #errorlog_file=N'C:MSSQL\Log\SQLAGENT.OUT'
GO
I just verified that it works, just make sure that the folder exist otherwise agent won't start
you probably also need to run this first, probably the proc above is disabled (by default)
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC master.dbo.sp_configure 'Agent XPs', 1
RECONFIGURE
This is the best solution if you have made Typo when entering a new path. Can be confirmed with the registry setting: find

Resources