If you can use SQLCMD mode in SSMS (SQLCMD Mode in the Query menu) or execute your script with sqlcmd.exe
, you can use a SQLCMD scripting variable:
:setvar ID "test"
CREATE DATABASE [$(ID)]
ON PRIMARY ( NAME = ['$(ID)_Primary'], FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\$(ID).mdf' , SIZE = 211968KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON ( NAME = ['$(ID)_log'], FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\$(ID)_log.ldf' , SIZE = 149696KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
From the command line, you would need to comment out the :setvar ID "test"
statement (i.e. --:setvar ID "test"
) and run the script like so...
sqlcmd.exe -E -i YourScript.sql -v ID="real"
...assuming Windows authentication, a local, default instance of SQL Server, and YourScript.sql
in the current directory.
The key is the -v
command-line option to specify the name of the SQLCMD variable you wish to set and its value.
Using a SQLCMD variable like this is essentially what SSDT does under the hood.