Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 dynamic restore dbs script problem

Author  Topic 

crownclit
Starting Member

20 Posts

Posted - 2012-05-22 : 19:46:47
Hello, I am trying to generate dynamic sql to restore databases. Looks like I am having problems with single quotes trying to separate string path to use 2 variables. One to restore path and second is for backup file name. This drives me a little crazy as I cannot generate proper sql. Could you please help?

Here is first script which when output to a file generates a second sql with error in the backup path.


---------------------------------------
SET NOCOUNT ON
GO

PRINT '--Restoring Databases'
PRINT 'DECLARE @FPath VARCHAR(255)'
PRINT 'Set @FPath = ' + '''C:\Insert backup file path here\'''

SELECT
'USE [' + name + ']
GO
'
+
'
RESTORE DATABASE [' + name + '] FROM DISK = N' + ''' + @FPath + ''' + name + '.bak'' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
GO

'
FROM sys.databases
WHERE name not in ('master','tempdb','model','msdb','ReportServer','ReportServerTempDB')
--------------------------------------



and here is the output with problem


--------------------------------------
--Restoring Databases
DECLARE @FPath VARCHAR(255)
Set @FPath = 'C:\Insert backup file path here\'

USE [test]
GO

RESTORE DATABASE [test] FROM DISK = N' + @FPath + 'test.bak' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
GO

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2012-05-22 : 19:58:15
Try this: http://weblogs.sqlteam.com/tarad/archive/2005/11/08/8262.aspx

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

crownclit
Starting Member

20 Posts

Posted - 2012-05-22 : 21:27:08
thank you Tara for your sample but i was wondering if i could get some help fixing mine.
Go to Top of Page
   

- Advertisement -