2016-11-29 38 views
0

我有以下腳本來還原數據庫。在這行:如果我硬編碼位置使用數據庫還原腳本說,路徑傳遞到FROM磁盤使用變量時無法打開備份設備

Msg 3201, Level 16, State 2, Line 24 Cannot open backup device 'C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Backup\C'. Operating system error 2(The system cannot find the file specified.). Msg 3013, Level 16, State 1, Line 24 RESTORE DATABASE is terminating abnormally.

FROM DISK = @backup_location --N'C:\Temp\TempDB.bak'

如果我使用@backup_location變量上面,它失敗,出現錯誤

FROM DISK = N'C:\Temp\TempDB.bak'

它工作正常。

如何使用變量來指定數據庫路徑?

USE [master] 

Go 

-- DECLARE VARIABLES: 
DECLARE @dbname SYSNAME 
DECLARE @backup_location VARCHAR 

SET @dbname = 'TempDB'; 
SET @backup_location = N'C:\Temp\TempDB.bak'; 

-- BEGIN: KILL ACTIVE CONNECTIONS 
Declare @spid int 
Select @spid = min(spid) from master.dbo.sysprocesses 
where dbid = db_id(@dbname) 
While @spid Is Not Null 
Begin 
     Execute ('Kill ' + @spid) 
     Select @spid = min(spid) from master.dbo.sysprocesses 
     where dbid = db_id(@dbname) and spid > @spid 
End 
-- END: KILL ACTIVE CONNECTIONS 

-- RESTORE DB: 
RESTORE DATABASE @dbname 
    FROM DISK = @backup_location --N'C:\Temp\TempDB.bak' 
    WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5 

Go 

謝謝你的時間。

回答

0

更改的最後幾行:

-- RESTORE DB: 
declare @statement varchar(max) 
--allow for quotation marks in @backup_location 
select @statement = 
    'RESTORE DATABASE ' + @dbname + 
    'FROM DISK = ''' + replace(@backup_location, '''', '''''') + 
    'WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5' 
exec (@statement) 
0

@codenoir,感謝您的答覆。一旦我看到你的varchar(max),我將@backup_location變量聲明更改爲相同,並且它不需要exec。

所以最後的代碼是:

USE [master] 

GO 

-- DECLARE VARIABLES: 
DECLARE @dbname SYSNAME 
DECLARE @backup_location VARCHAR(MAX) 

SET @dbname = 'TestDB'; 
SET @backup_location = N'C:\Temp\TestDB.bak'; 

-- BEGIN: KILL ACTIVE CONNECTIONS 
DECLARE @spid INT 
SELECT @spid = MIN(spid) FROM master.dbo.sysprocesses 
WHERE dbid = DB_ID(@dbname) 
WHILE @spid Is Not Null 
BEGIN 
     EXECUTE ('Kill ' + @spid) 
     SELECT @spid = MIN(spid) FROM master.dbo.sysprocesses 
     WHERE dbid = db_id(@dbname) and spid > @spid 
END 
-- END: KILL ACTIVE CONNECTIONS 

-- RESTORE DB: 
RESTORE DATABASE @dbname 
    FROM DISK = @backup_location 
    WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5 

Go