Passing Command-Line Variables

Question: I want to pass two variables, @dept and @site, into a T-SQL script that I can run from the command line by using OSQL. How do I write the OSQL script to pass the desired variables?

Answer: You can't directly pass parameters as part of the OSQL command-line utility, but you have several alternatives for solving your problem.

Related: Take Advantage of OSQL and BCP Without Having to Remember All Their Command-Line Option

For example, suppose you want to run the following T-SQL command:

SELECT * FROM orders 
WHERE orderid = 10248

But you want to specify the OrderId value on the command line instead of in the script. One option is a pure SQL Server approach to the problem. OSQL won't let you pass in parameters, but you can use the sp_executesql stored procedure, which can process parameterized SQL. (For detailed information about sp_executesql, see SQL Server Books OnlineBOL.) The following example lets you pass parameters into a T-SQL command but doesn't completely address how to pass a parameter as part of an OSQL command-line session (remember that you must issue the OSQL command from a command prompt):

osql -E -MyServer -Q "EXECUTE sp_
executesql N'SELECT * FROM northwind..
orders WHERE OrderId = @OrderId' ,
N'@OrderId int' ,@OrderId = 10248"

Another solution relies on the power of Windows to handle the parameterization for you. For DBAs who aren't familiar with Windows-level command-file processing, a batch file is a text file that has a .bat extension. Windows treats batch files as executables that run in the Command Prompt environment. You can think of batch files as mini programs that Windows runs.

You can simply create a file called SQLVariableBatch.bat, and put the following text in it:

osql -E -MyServer -Q "SELECT * 
FROM northwind..orders 
WHERE OrderId = %1"

From the directory where you saved the .bat file, issue the following command from a command prompt window:

SQLVariableBatch 10248

When running this command, Windows will replace the %1 in the SQLVariableBatch.bat file with what comes after the batch file's name in the command line—in this case, 10248. This is a simple example of batch processing in Windows; to learn more about batch files, see the Windows Help files.

You can also use Windows Scripting Host (WSH) to manage the parameterization. Using WSH for scripting and batch processing is much more flexible and powerful than using simple Windows batch files. I'm not a WSH expert, so I don't include an example of this solution, but I wanted to note that the option exists.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.