T-sql – Read TSQL variable from Temp Table

t-sql

I am hacking around trying to write a script to restore a backup from a known folder location. The location will only ever contain one backup file. I have come up with this so far, but I don't know how to get the value from the temp table into the restore database command.

CREATE TABLE #tempFileTable (FName VARCHAR(8000),Depth INTEGER, Files INTEGER)

INSERT INTO #tempFileTable
EXEC xp_dirtree 'S:\', 1, 1

SELECT TOP 1 FName FROM #tempFileTable

DROP TABLE #tempFileTable

DECLARE @DBName varchar(255) = 'DatabaseName'

RESTORE DATABASE @DBName FROM  DISK = ??? WITH  FILE = 1

GO

Best Answer

May be you can try this:

CREATE TABLE #tempFileTable (FName VARCHAR(8000),Depth INTEGER, Files INTEGER)

INSERT INTO #tempFileTable
EXEC xp_dirtree 'D:\Test1', 1, 1

SELECT TOP 1 Fname FROM #tempFileTable;

DECLARE @DBName varchar(255) = 'Test'

select 'RESTORE DATABASE ' + @DBName + ' FROM  DISK = D:\Test1\' + fname +  ' WITH  FILE = 1' 
from #tempFileTable

DROP TABLE #tempFileTable

GO

Output:

RESTORE DATABASE Test FROM  DISK = D:\Test1\ReportServer.bak WITH  FILE = 1