I'm trying to write a script which automatically restores a database backup. I know I can use the following RESTORE command:
RESTORE DATABASE [DBRestoredName]
FROM DISK = N'C:\path\to\backup.bak'
WITH FILE = 1,
MOVE N'DBNAME' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\DBNAME.mdf',
MOVE N'DBNAME_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\DBNAME.ldf',
NOUNLOAD
The problem with this is I want to be able to determine the SQL server's data location (i.e. the TO path) at run-time so the restored database is placed consistently alongside other databases on this server.
The database being restored won't exist on the server it's being restored to and I require the MOVE statements as the source server is likely to be SQL server 2005 and the target is 2008 therefore the file paths included in the backup file are not desirable.
So what ways could I determine the SQL data location programmatically?
To specify the new location of the database files, select the Files page, and then select Relocate all files to folder. Provide a new location for the Data file folder and Log file folder. For more information about this grid, see Restore Database (Files Page). On the Options page, adjust the options if you want.
You have two native options for finding out where the SQL server stores its database files: either right-click on the instance name in SQL Server Management Studio (SSMS) and navigate to the 'Database Settings' tab, or use a T-SQL query.
Right-click the SQL Server instance and select Properties. Select the Database Settings section. At the bottom of this window, you should see the Backup default location.
1. Launch SSMS and connect to your instance, right-click the database which stuck in restoring, select Tasks > Restore > Transaction Log… 2. In the prompt window, General page, uncheck all log backups in Select the transaction log backups to restore section, then click OK.
The only viable solution I found is inspecting the registry from your T-SQL code:
DECLARE @filepath NVARCHAR(260)
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'DefaultData',
@filepath output, 'no_output'
SELECT @filepath as 'Your default data directory'
I could have sworn that data path would be stored somewhere in a SERVERPROPERTY
or a Dynamic Management View (DMV) - but no luck ......
Update: as @Mike pointed out - in SQL Server 2012 and newer, that information is available as a SERVERPROPERTY
:
SELECT
DefaultDataPath = SERVERPROPERTY('InstanceDefaultDataPath'),
DefaultLogPath = SERVERPROPERTY('InstanceDefaultLogPath')
You can query this from the sys.database_files view in the database you wish to restore alongside physically. You will have to strip off the file name from the end of the physical_name column.
select * from sys.database_files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With