Using SQL Server sqlcmd scripting variables

Problem

SQLCMD is not just a script execution tool. It gives us access to internal variables and commands that we can use to automate code execution in SQL Server. In this tip I will show you how you can use the SQLCMD scripting variables.

Solution

The utility SQLCMD, has been around since SQL Server 2005 as a replacement for osql. Usually sqlcmd was overlooked by the majority of Database Administrators, but with the arrival of SQL Server on Linux this is changing. That’s because on Linux it is very common to use the console to do administrative tasks. In fact, you can do anything with the console.

SQLCMD Commands

An interesting feature of SQLCMD is the ability to use commands inside a script and in the console mode. For example if you are writing code in console mode and you need to see the operating system environment variables or a file name you don’t need to exit the tool or abort what you are doing or end your current batch with GO.

You can just run something like this:

SELECT @@SERVERNAME;
:listvar
GO   

On the next screen capture you will see the output of the previous script using sqlcmd. Notice that you can use sqlcmd commands while you are writing a batch.

sqlcmd - Description: You can use sqlcmd commands without ending the current batch.

For those of you who know something about C programming, the sqlcmd commands are like preprocessor directives. In other words, they change the way the script is executed.

The following table includes the available sqlcmd commands and descriptions. The commands are case insensitive.

CommandDescription
GO [ count]Executes the current batch [count] times.
:ListPrints the contents of the statements cache.
[ :] RESETClears statement cache.
:Error <filename>Redirects error messages to <filename>.
[ :] EDStarts a text editor. (Usually edit.exe, so this command may be just for backward compatibility).
:Out <filename>Redirects the output to <filename>.
[ :] !!<command>Executes the shell command specified on <command>.
:Perftrace <filename>Creates and redirects performance trace information and saves it into <filename>.
[ :] QUITExits sqlcmd.
:Connect <server\instance>Connects to the specified target.
[ :] EXIT [statement]Allows you to use the result of a SELECT statement as the return value from sqlcmd.
:On Error [ exit | ignore]Sets the behavior of sqlcmd regarding to errors.
:r <filename>Loads the content of <filename> into the statement cache. If the file does not contain a line with GO statement, then you have to enter it manually in order to execute the file contents.
:HelpDisplays sqlcmd help.
:ServerListLists SQL Servers on the network.
:XML [ ON |  OFF]Handles XML output format.
:Setvar [Variable] [Value]Set/unset user variables.
:ListvarShows a list of the currently set scripting variables.

SQLCMD Internal Variables

There is an advantage of using scripts with sqlcmd internal variables over pure T-SQL scripts, which is portability. Imagine a scenario where you have a script that needs the name of the current server or the workstation where the script is being executed. In this situation, if you use a pure T-SQL script you will need to modify the references to the server and workstation in the entire script. This is not only a time consuming task, it is also prone to mistakes. Fortunately sqlcmd has internal variables to aid us on this matter.

The following table shows a list of the internal variables for sqlcmd and the descriptions. The variable names are case insensitive.

VariableRead - WriteDefault ValueDescription
SQLCMDUSERRead OnlyN/ACurrent user login name.
SQLCMDPASSWORDN/AN/ACurrent user password.
SQLCMDSERVERRead Only“DefaultLocalInstance”The name of the instance and server you are connected to.
SQLCMDWORKSTATIONRead Only“ComputerName”Your computer name.
SQLCMDDBNAMERead OnlyN/AThe name of the database you specified with the -d switch.
SQLCMDLOGINTIMEOUTRead Write“8” (seconds)Time before the login attempt fails.
SQLCMDSTATTIMEOUTRead Write“0” = wait indefinitelyQuery timeout.
SQLCMDHEADERSRead Write“0”Number of lines to print result set headers.
SQLCMDCOLSEPRead Write” ”Column separator character.
SQLCMDCOLWIDTHRead Write“0”Output column width.
SQLCMDPACKETSIZERead Only“4096”The data transfer unit size used by sqlcmd.
SQLCMDERRORLEVELRead Write“0”Level of error message shown.
SQLCMDMAXVARTYPEWIDTHRead Write“256”This is the limit of characters used to display variable data types like varchar or json to enumerate a few.
SQLCMDMAXFIXEDTYPEWIDTHRead Write“0” = unlimitedThis is the limit of characters used to display fixed data types, like varchar(n) or numeric to enumerate a few.
SQLCMDEDITORRead Write“edit.com”Default text editor.
SQLCMDINIRead Only“”Startup script name.

When you need to reference a variable, either internal or user defined, you must use the following notation where VARIABLE is the variable name:

$(VARIABLE)   

Consider the following script as an example:

SELECT top 5 session_id, login_name 
FROM sys.dm_exec_sessions 
WHERE login_name = '$(SQLCMDUSER)'   

In the previous script we are querying sys.dm_exec_sessions system view for open sessions by the user who runs the script.

Notice that I have enclosed the variable with quotation marks. That’s because the interpretation of the variable relies on sqlcmd. In other words, there is no difference for the SQL Server instance if you use the variable or just write the login name.

The following screen capture shows the output of the previous query.

Sqlcmd Variables - Description: Using internal variables whithin the T-SQL code.

Next Steps

Leave a Reply

Your email address will not be published. Required fields are marked *