Passing parameters to a Windows Batch file

Sometime back I responded to a question on one of the forums. The user had a deployment script which was a .cmd file and he wanted to modify it in such a way that it accepts a few parameters. He wanted to execute that file by passing the database name as a variable.

Parameters passed to a .cmd file can be read using  %[parameter#] inside the file. %1 will hold the first parameter passed in the command prompt, %2 for the second parameter and so on.

The original script looked something like this.

sqlcmd -S . -d DatabaseName -i C:input.sql -h-1

In order to get the DatabaseName dynamically from the command prompt, the script needs to be modified to include  %1 instead of the DatabaseName.

sqlcmd -S . -d %1 -i C:input.sql -h-1

When I pass the value master to this parameter, the output would look like this.

This parameter can also be modified to get only the drive letter, file extension of the variable. This article has the complete list of the batch parameters.

Leave a Reply