sql-servervisual-studiot-sqldatabase-project

How do I change the filepath using Visual Studio Database Project?


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?


Solution

  • 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.

    1. In the VS database project IDE, select SQLCMD Variables in the database project properties and enter the variable name and a default value:

    enter image description here

    1. Specify the SQLCMD variable name enclosed in $() in the T-SQL script:

      declare @backupFilePath varchar(max) = N'$(BackupFilePath)'

    2. Load the publish profile and specify the desired target-specific value:

    enter image description here

    1. Save the modified publish profile for future use and/or publish.

    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.