Question

I'm trying to create a generic script to create a database and want to pass the database name as a variable; but it's not working.

Here is my code so far

DECLARE @ID sysname; 

SET @ID = 'test'
SET @ID = QUOTENAME(@ID)

CREATE DATABASE @ID

ON  PRIMARY
( NAME = [' + @ID + '], 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%)

which gives me the following error:

Incorrect syntax near '@ID'.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top