Re: Backup DB with dynamic sql - want to substitute in dbname and disk file path
Hope I can explain this. Below is a small snippet of code. I want to set @SQLTemplate_TSQL once at the top of the script and then execute the SET @SQLCommand and sp_executesql in a loop that reads a list of databases. It all works, except for the BACKUP DATABASE. Right now it evaluates when the SET @SQLTemplate_TSQL is evaluated. I want it to evaluate when it is executed. I want the DB_NAME() of the USE @dbname.
-- change @dbname and @dbbackuppath DECLARE @SQLCommand NVARCHAR(MAX) DECLARE @SQLTemplate_TSQL NVARCHAR(MAX) DECLARE @dbname varchar(128) = 'Bank04' -- one time setting of @SQLTemplate_TSQL set @SQLTemplate_TSQL = ' DECLARE @dbbackuppath varchar(128) = ''''d:\backups'''' IF RIGHT(@dbbackuppath, 1) <> ''''\'''' SET @dbbackuppath = @dbbackuppath + ''''\'''' SET @dbbackuppath = @dbbackuppath + DB_Name() + ''''.bak'''' PRINT @dbbackuppath BACKUP DATABASE ' + DB_NAME() + ' to DISK=''' + QUOTENAME(@dbbackuppath, CHAR(39)) + ''' ' -- Execute this several times over different databases SET @SQLCommand = ' USE ' + QUOTENAME(@dbname) + '; EXEC(''' + @SQLTemplate_TSQL + ''') ' PRINT @SQLCommand EXECUTE sp_executesql @SQLCommand