T-SQL恢复包含脚本和变量的数据库

时间:2016-07-14 07:29:40

标签: sql-server tsql database-restore

出现问题,但无法找到错误......

我想在程序中恢复数据库,但不能使用变量...

DECLARE @sql as NVARCHAR(1000)
DECLARE @targetDBname as NVARCHAR(20) = 'BO_9999'
DECLARE @backupFileNamePath as NVARCHAR(100) = '\\SRV015\C$\temp\BO_1767_Schulung_2016-07-13_22-36-28.bak'
DECLARE @masterDBname as NVARCHAR(20) = 'BO_1767_Schulung'
DECLARE @targetMDFfilePath as NVARCHAR(100) = 'Y:\CADTOOLS\DB\BO_9999.mdf'
DECLARE @masterLogname as NVARCHAR(30)= 'BO_1767_Schulung_log'
DECLARE @targetLogFilePath as NVARCHAR(100) = 'Y:\CADTOOLS\LOG\BO_9999_log.LDF'

SET @sql = '''RESTORE DATABASE ' + @targetDBname
SET @sql = @sql + ' FROM DISK = ''''' + @backupFileNamePath + ''''''
SET @sql = @sql + ' WITH FILE = 1'
SET @sql = @sql + ', MOVE ''''' + @masterDBname + ''''''
SET @sql = @sql + ' TO ''''' + @targetMDFfilePath + ''''''
SET @sql = @sql + ', MOVE ''''' + @masterLogname + ''''''
SET @sql = @sql + ' TO ''''' + @targetLogFilePath + ''''''
SET @sql = @sql + ', NOUNLOAD, REPLACE, STATS = 10'''

PRINT @sql
EXEC (@sql)

--THIS COMMAND RUNS BUT I CANT GET THE COMMAND IN AN EXEC WITH VARIABLES
--RESTORE DATABASE BO_9999 FROM DISK = '\\SRV015\C$\temp\BO_1767_Schulung_2016-07-13_22-36-28.bak' WITH  FILE = 1, MOVE 'BO_1767_Schulung' TO 'Y:\CADTOOLS\DB\BO_9999.mdf', MOVE 'BO_1767_Schulung_log' TO 'Y:\CADTOOLS\LOG\BO_9999_log.LDF', NOUNLOAD, REPLACE, STATS = 10

任何人都可以帮助我......网络中的页面仍然很多......但是无法运行?!

谢谢@all 它以这种方式运行:     从磁盘恢复数据库BO_9999 =' \ SRV015 \ C $ \ temp \ BO_1767_Schulung_2016-07-13_22-36-28.bak' WITH FILE = 1,MOVE' BO_1767_Schulung' TO' Y:\ CADTOOLS \ DB \ BO_9999.mdf',MOVE' BO_1767_Schulung_log' TO' Y:\ CADTOOLS \ LOG \ BO_9999_log.LDF',NOUNLOAD,REPLACE,STATS = 10

这样:     RESTORE DATABASE @targetDBname FROM DISK = @backupFileNamePath WITH FILE = 1,MOVE @masterDBname to @targetMDFfilePath,MOVE @masterLogname TO @targetLogFilePath,NOUNLOAD,REPLACE,STATS = 10

但最后我需要像这样在另一个链接服务器上运行它 [server \ instance]

的EXEC(@sql)

???

0 个答案:

没有答案