How to insert into a temp table the info given by RESTORE FILELISTONLY / HEADERONLY / VERIFYONLY

LaBracca picture LaBracca · Aug 5, 2010 · Viewed 10k times · Source

How to insert the resultset given by the commands

RESTORE FILELISTONLY
RESTORE  HEADERONLY
RESTORE VERIFYONLY

into an automatically generated temp table ?

I would like to use a technique similar to (so the table is auto created, with all the columns matching the resultset's columns)

SELECT * INTO #TempTable 
FROM (RESTORE FILELISTONLY FROM DISK = 'c:\Test\Test.bak')

But this doesn't work. If I could populate a TempTable I could then be able to use the information contained in it in a following SQL Statement (in my case a restore DB statement in which I need to use some strings contained in the resultset given by RESTORE FILELISTONLY)

I am using sql server 2008.

Answer

Pondlife picture Pondlife · Aug 5, 2010

Personally, this is one scenario where I would avoid pure TSQL and use an external script or program. Depending on what you're trying to do, you might find that using Smo from Powershell or .NET completely avoids the need for TSQL anyway. I say that because working with backups always seems to lead to working with files outside the database, and then TSQL is just too awkward.

Having said all that, if you're sure that you must do this in TSQL, then you can do something like this:

insert into dbo.BackupFiles (LogicalName, PhysicalName, ...)
exec('RESTORE FILELISTONLY FROM DISK = ''c:\Test\Test.bak''')

Or to be a bit nicer:

declare @Command nvarchar(4000)
-- you can build the command string some other way, of course
set @Command = N'RESTORE FILELISTONLY FROM DISK = ''c:\Test\Test.bak'''

insert into dbo.BackupFiles (LogicalName, PhysicalName, ...)
exec sp_executesql @Command

You would still have to create the table first, though, which is no big deal and makes sense anyway if you do this a lot. Books Online lists the data type for each column in the result set, but at least for me (SQL2008 SP1) the documentation does not match the actual result set so you might need to tweak it.