declare @databasename varchar(50) = 'aDatabase'
declare @dbNameTimeStamp varchar(100) = 'aDatabase_20230404_0916'
declare @backupFilePathForDev varchar(max) = 'N''J:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\'
declare @backupFilePathForProd varchar(max) = 'N''K:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\'
declare @backupFilePath varchar(max) = 'N''?:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Backup\'
print('backup database ' + @databasename)
exec('BACKUP DATABASE [' + @databasename + '] TO DISK = ' + @backupFilePath + @dbNameTimeStamp + '.bak'' WITH NOFORMAT, NOINIT, NAME = N'''+ @databasename + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10')
insert into MaintenancedFile([filename], filetype, maintenancetype, backuptimestamp)
values(@databasename, 'db', 'backup', GETDATE())
The path for @backupFilePath
is different depending on which server I deploy to.
Is there some way to change the path depending on which publish profile I use through Visual Studio Database Project?
Use database project SQLCMD variables in T-SQL scripts when values may differ by the publish action target. The desired values can be set in a publish profile or specified via command-line during publish.
Specify the SQLCMD variable name enclosed in $()
in the T-SQL script:
declare @backupFilePath varchar(max) = N'$(BackupFilePath)'
Load the publish profile and specify the desired target-specific value:
Note system-defined SQLCMD variables are also set during the publish action. You could also leverage these in your script (e.g. DatabaseName
) without creating a user-defined SQLCMD variable.