I\'m not very fluent with SQL Server commands.
I need a script to restore a database from a .bak file and move the logical_data and logical_log files to a specific p
I have created a new version based on the answers found here. It should work with the latest versions of SQL Server.
Provided with a back-up location, it restores the DB and moves the MDF and LDF files to a specified location.
declare @databaseName nvarchar(max);
declare @backUpDiskLocation nvarchar(max);
declare @physicalMDFLocation nvarchar(max);
declare @physicalLDFLocation nvarchar(max);
set @databaseName = '[]';
set @backUpDiskLocation = 'C:\SQL-BACKUP\.bak';
set @physicalMDFLocation = 'C:\SQL\SQLData\.mdf';
set @physicalLDFLocation = 'C:\SQL\SQL-LOG\.LDF'
if (DB_ID(@databaseName)) is not null
Begin
DECLARE @kill varchar(8000); SET @kill = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = DB_ID(@databaseName)
EXEC(@kill);
DECLARE @Alter nvarchar(max); SET @Alter = 'ALTER DATABASE ' + @databaseName +' SET offline WITH Rollback Immediate'
EXEC (@Alter)
END
declare @sql nvarchar(max)
set @sql = N'restore filelistonly from disk=''' + @backUpDiskLocation +'''';
select @sql
create table #filelist (LogicalName nvarchar(128), PhysicalName nvarchar(260), Type char(1), FilegroupName varchar(10), size bigint, MaxSize bigint, field int, createlsn bit, droplsn bit, uniqueid uniqueidentifier, readonlylsn bit, readwritelsn bit, backupsizeinbytes bigint, sourceblocksize int, filegroupid int, loggroupguid uniqueidentifier, differentialbaselsn bit, differentialbaseguid uniqueidentifier, isreadonly bit, ispresent bit, tdethumbprint varchar(5), SnapshotUrl nvarchar(128));
insert into #filelist exec sp_executesql @sql;
ALTER TABLE #filelist add id int identity(1,1)
update #filelist set PhysicalName = @physicalMDFLocation where [id]= 1
update #filelist set PhysicalName = @physicalLDFLocation where [id]= 2
select * from #filelist
set @sql = N'RESTORE database '+ @databaseName +' from disk = '''+ @backUpDiskLocation +''' with replace, ';
select @sql
select @sql = @sql + N' move ''' + LogicalName + N''' to ''' + PhysicalName + N''',' from #filelist;
set @sql = substring(@sql, 1, len(@sql)-1); -- remove last ','
select @sql
exec sp_executesql @sql;
drop table #filelist