根据“仅还原文件列表”结果创建临时表

时间:2018-10-11 15:17:39

标签: sql-server tsql restore

我试图创建一个包含LogicalName,PhysicalName,Type和FileGroupName的临时表。我需要此脚本是SQL版本不可知的。

RESTORE FILELISTONLY FROM DISK = 'C:\BackupFile'

我可以通过首先创建表然后插入信息来完成此操作,但是由于每个版本RESTORE FILELISTONLY FROM DISK的结果集更改,因此每个SQL版本需要一个脚本。

我不确定是否可以,但是任何帮助都会很有帮助

1 个答案:

答案 0 :(得分:0)

您可以使用INSERT INTO EXEC

CREATE TABLE temp(...);    

INSERT INTO temp(LogicalName, PhysicalName, Type, FileGroupName,...)
EXEC('RESTORE FILELISTONLY FROM DISK = ''C:\BackupFile''');

SELECT * FROM temp;

编辑:

成为独立于版本getting version

DECLARE @version NVARCHAR(100) = 
 CASE 
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '8%' THEN 'SQL2000'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '9%' THEN 'SQL2005'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN 'SQL2008'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN 'SQL2008 R2'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN 'SQL2012'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN 'SQL2014'
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN 'SQL2016'     
     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '14%' THEN 'SQL2017' 
     ELSE 'unknown'
  END;

-- pseudocode
IF @version = 'SQL2017'
  EXEC('CREATE TABLE temp(col1, col2, col3)');

IF @version = 'SQL2016'
  EXEC('CREATE TABLE temp(col1, col2, col3, col4)');

IF @version = 'SQL2014'
  EXEC('CREATE TABLE temp(col1, col2, col3, col4, col5)');

-- no column list(blind insert)
EXEC('INSERT INTO temp   
      EXEC(''RESTORE FILELISTONLY FROM DISK = ''''C:\BackupFile'''' '')');
GO

-- common columns only
SELECT LogicalName, PhysicalName, Type, FileGroupName
FROM temp;