一般情况是,我尝试使用下面的脚本自动还原备份列表。我将所有备份都放在同一个文件夹中,然后将备份的名称放在表中以便于检索。最后,我放置了一个游标,该游标每次都指向备份并进行还原。现在执行脚本时,出现此错误:
消息3234,级别16,状态2,第82行逻辑文件 'OP38MLG_db_201903040000_DATA'不是数据库的一部分 'OP38MLG_db_201903040000'。使用RESTORE FILELISTONLY列出 逻辑文件名。 Msg 3013,Level 16,State 1,Line 82 RESTORE DATABASE正在异常终止。
当我分别还原每个备份时,操作成功结束,但是当我尝试还原列表时出现错误。
DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
-- specify database backup directory
SET @path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\'
DECLARE @backuppath NVARCHAR(256) -- path for backup files
DECLARE @datapath VARCHAR(256) -- path for data files
DECLARE @logpath VARCHAR(256) -- path for log files
DECLARE @backupfileName VARCHAR(256) -- filename for backup
DECLARE @datafileName VARCHAR(256) -- filename for database
DECLARE @logfileName VARCHAR(256) -- filename for logfile
DECLARE @logName VARCHAR(256) -- filename for logfile
DECLARE @dataName VARCHAR(256)
-- specify database backup directory
SET @backuppath = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\'
SET @datapath = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\'
SET @logpath = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\'
print 'backup path is ' + @backuppath
print 'data path is ' + @datapath
print 'log path is ' + @logpath
/*Table to hold each backup file name in*/
CREATE TABLE #List(fname varchar(200),depth int, file_ int)
INSERT #List
EXECUTE master.dbo.xp_dirtree @backuppath, 1, 1
SELECT * FROM #List
DECLARE files CURSOR FOR
SELECT fname FROM #List
OPEN files
FETCH NEXT FROM files INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @cleanname AS VARCHAR(255)
SET @cleanname = REPLACE(@name, '.BAK', '')
PRINT @cleanname
SET @backupfileName = @backuppath + @name
SET @datafileName = @datapath + @cleanname + '.MDF'
SET @logfileName = @logpath + @cleanname + '_log.LDF'
SET @logName = @cleanname + '_log'
SET @dataName = @cleanname + '_DATA'
print 'backup file is ' + @backupfileName
print 'data file is ' + @datafileName
print 'log file is ' + @logfileName
USE [master]
RESTORE DATABASE @cleanname
FROM DISK = @backupfileName
WITH FILE = 1,
MOVE @dataName TO @datafileName,
MOVE @logName TO @logfileName,
NOUNLOAD, STATS = 5
FETCH NEXT FROM files INTO @name
END
CLOSE files
DEALLOCATE files
DROP TABLE #List
GO
我希望在输出中可以还原备份,并且可以在数据库栏中看到它们,但是实际输出是我上面提到的错误。
答案 0 :(得分:0)
SQL Server数据库由许多“ 逻辑文件”组成。还原数据库时,您需要说出这些文件的存储位置。您正在执行此操作,但是您的代码对这些逻辑文件的名称进行了假设。您假设它们是 FileName _Data 和 FileName _Log 。错误消息告诉您在这种情况下是错误的。如果可以运行以下查询,请查看LogicalName字段以查看此.BAK文件的实际值。
RESTORE FILELISTONLY FROM DISK = N'C:\MyBackups\OP38MLG_db_201903040000.bak'
多年来,这在我身上发生了很多次。找出实际的逻辑文件名总是令人惊讶。