This article aims to help you understand the sqlcmd utility. Of course, this is a tool that most of us have used on multiple occasions since the tool has been around for a decade. However, as a solid starting point, this article provides some examples to help you understand the tool from different angles.
This article covers:
- How to enable SQLCMD
- Some key points to remember
- SQLCMD with Script Variables in SSMS
- Passing variables (or arguments) as a T-SQL and/or as an SQL script file
- SQLCMD with Windows Script and Script Variables in SSMS
What is SQLCMD?
sqlcmd is a command line utility that is part of the default installation of SQL Server 2005 or later and allows you to interactively interface with any instance of SQL Server to perform the following tasks:
- Execute Transact-SQL (T-SQL) statements in SSMS
- Call a T-SQL script file
- Using environment variables in command mode
- Save the output results of executed queries to a specified text file
Why SQLCMD?
sqlcmd is a simple yet powerful scripting environment that helps automate many SQL Server related tasks. For example, you can write and run a script that connects you to a specific instance of SQL Server, runs a script from a specified path, and redirects the output to a specific file.
Most of us SQL database administrators are already using PowerShell. The sqlserver module's Invoke-SqlCmd cmdlet, which has been part of every SQL Server distribution since 2008, contains most of the functionality of sqlcmd. Also, in SQL Server Management Studio, we have a SQLCMD mode that simulates the features of sqlcmd and accepts some of the commands that are not part of the T-SQL language.
sqlcmd was an extension of the osql and isql command line utilities, containing a variety of parameters and options to allow automation of various administrative tasks.
- Binding SQL into a .bat file is easy.
- It runs interactively on different operating system platforms.
- It's easy to pass command line arguments to a sql file with sqlcmd.
How to enable SQLCMD
OK, so sqlcmd is a great tool; we are all convinced of it. Now let's talk about how to use the Query Editor in SSMS to write statements as sqlcmd scripts. The following example covers integrating Windows system commands and T-SQL statements into a single script.
It is important to remember that sqlcmd mode is not enabled by default. To switch to sqlcmd mode in SSMS Query Editor, follow these steps:
- In Object Explorer, right-click SQL Server and click New Query
OR
Open a new Database Engine Query Editor window. - In the query editor, clickSQLCMD-ModusName.
To enable SQLCMD script mode:
- Go to SSMSToolmenu, selectoptions.
- expand thisquery executiontab and selectservidor SQL, tightenGenerallybook page.
- check the boxBy default you open new queries in SQLCMD mode.
Some important points to remember
- SQLCMD commands must be prefixed with a colon. This shows the difference between SQLCMD and Transact-SQL commands.
- The :CONNECT keyword is used to connect to another server usingsame session context.
- Operating system commands used for the demo (in this case, if any) and del commands must begin with two exclamation marks (!!). O !! indicate that the commands are operating system commands executed using the cmd.exe command processor. In this example, the operating system command, if present, $(file1) del $(file1) is passed as arguments to cmd.exe.
- Variables used as part of the SQLCMD script are case sensitive. For example, if we query the environment variables, we will see that COMPUTERNAME and computername are two different variables in the output. In the first case, the environment variable is queried to return the computer name, while in the second case, SSMS is unable to resolve the variable and reports an error.
1 2 3 4 5 | :to connecthqdbsp18 PRESS '$(COMPUTER NAME)' AND :to connecthqdbsp17 PRESS '$(Computer name)' |
Examples of SQLCMD
The following example defines a common integration of operating system commands and SQL statements.
Variables are defined with SETVAR, connections are established with the CONNECT keyword, operating system commands are defined with !! defined, the output file is declared with the OUT keyword and SQL statements are placed to retrieve the results based on the connection string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | --VariableExplanation :setvarSubscriber1HQMESRP01 :setvarSubscriber2HQMESRP02 :setvarfor data1 C:\data1.TXT :setvarDatei2 C:\data2.TXT --checkfor To diefileE extinguishSe exist !!Se exist $(for data1) do $(for data1) !!Se exist $(Datei2) do $(Datei2) --to connectFor For To dieEnrollment 1 :To connect $(Subscriber1) --redirectTo dieSQLExitFor file :outside of $(for data1) to choose * outside of [MES_REPL_Rpt_AP]..tb_F4801_woheaderWoWadoco=2520079 to choose * outside of [MES_REPL_Rpt_AP]..tb_F4801_woheader_MESWowork order number=2520079 AND --to connectFor For To dieEnrollment 2 :To connect $(Subscriber2) --redirectTo dieSQLExitFor file :outside of $(Datei2) to choose * outside of [MES_HIST_AP]..tb_F4801_woheaderWoWadoco=2520079 to choose * outside of [MES_HIST_AP]..tb_F4801_woheader_MESWowork order number=2520079 |
SQLCMD with Script Variables and Windows Scripts in SSMS
In this example, the login is created on multiple servers. T-SQL, sqlcmd and Windows scripts are all integrated and run through the SSMS interface to create logins.
- Ativar XP_CMDSHELL
- Define T-SQL in a .sql file
- Create dynamic SQL
- check the output
STEP 1: In this step, xp_cmdshell will be activated. However, it is not a recommended option. This has been enabled for demo purposes only.
1 2 3 4 5 6 7 8 | sp_to set up 'Show advanced options', 1; AND RECONFIGURE; AND sp_to set up 'xp_cmdShell', 1; AND RECONFIGURE; AND |
STEP 2: An SQL file, SysAdminLoginCreation.sql, is created using the create login SQL statement.
1 2 3 4 | TO USE [Teacher] AND TO CREATEREGISTER [SQLShackTest] COMPASSWORD=N'SQLShackDemo123', DEFAULT_DATABASE=[Teacher], CHECK_EXPIRATION=OUTSIDE OF, CHECK_POLICY=OUTSIDE OF AND |
the file looks like this
We create a for loop to iterate through all SQL instances.
- Iterate over the input file.
- The FOR parameter %j defines the name of the SQL instance.
- Call sqlcmd with parameters as part of the command.
- Repeat for each data item.
1 | MEISTER..EXP_CMDSHELL 'für /f %j in (\\networkshare\IsDba\server.txt) do sqlcmd -S %j -i \\networkshare \IsDba\SysAdminLoginCreation.sql -E' |
sqlcmd executed successfully!
Let's check if logins are created on these servers
1 2 3 4 5 | :to connecthqdbsp18 to choose * outside ofsystem.System loginsWoName='SQLShackTest' AND :to connecthqdbsp17 to choose * outside ofsystem.System loginsWoName='SQLShackTest' |
Logins were also created for the listed servers.
Passing variables (or arguments) as T-SQL and SQL script file
We can pass the variables as input to T-SQL or SQL script file in sqlcmd command console. Script variables are declared with the :SETVAR keyword. Appropriate parameter values are passed to the T-SQL or SQL script file. Values enclosed in $(variable name) are fed to the SQLs at runtime. The -v (version) option is used to declare the parameters and pass them to the script. We can list any number of variables without separators between the parameters. Let's follow the example to better understand the mechanism:
- Oorder detailsis the name of the assigned tabletable nameVariable
- The select statement is prepared along with the tablename variable
1 2 3 4 5 | C:\from the user\ccov648>SQLCMD -S hdbt01\SQL2017 -E 1> to use Python2017 2> :SETVARtable nameSales Order Details 2> to choosePrincipal(10) * outside of $(table name); 3> and |
We can assume that the database name will be provided as an SQLCMD variable during the deployment process. We can provide the exact same file in all environments. The following example has two parameters, db and tablename. Input parameters are separated by a space.
1 | C:\from the user\ccov648>SQLCMD -S hdbt01\SQL2017 -E -EU N:\IsDba\Sales order details.sql -v database=Python2017table name=Sales Order Details |
Summary
The SQLCMD mode in SQL Server Management Studio (SSMS) provides an interface for executing SQL statements on various servers and platforms. This is really helpful in many cases. In this article, we discussed creating logins on different SQL Server instance versions. Likewise, we perform data validation between the two subscribers. We've also seen that if you have a complex SQL query that requires multiple inputs, the values can be passed as parameters to the T-SQL or SQL script file.
Also, we should bear in mind that SQLCMD mode only allows the use of commands from the sqlcmd environment from within SSMS, but without typical IntelliSense support or debugging support. Scripts that combine pure T-SQL and SQLCMD can be expensive to maintain. Use it wisely!
Index
Start Building Applications with SQL Server DevOps Tools |
SQLCMD Utility Overview in SQL Server |
The BCP (Bulk Copy Program) command in action |
Continuous Database Delivery (CD) with SQL Server Tools SqlPackage.exe |
All about MSSQL-Scripter, the cross-platform scripting tool for SQL Server |
Introduction to Azure Data Studio (ADS); Installation and initial configuration |
- Author
- recent posts
I'm a database technologist with over 11 years of hands-on experience with database technologies. I am a Microsoft Certified Professional with a Masters in Computer Applications.
My specialty is the development and implementation of cross-platform high availability and database migration solutions. Technologies currently being worked on are SQL Server, PowerShell, Oracle and MongoDB.
Show all posts by Prashanth Jayaram
Latest posts by Prashanth Jayaram(see it all)
- Ladder to SQL Essentials- 7. April 2021
- A brief overview of database verification in SQL- January 28, 2021
- How to configure Azure Data Sync between Azure SQL Databases and on-premises SQL Server- January 20, 2021
Related posts:
- Working with PowerShell's Invoke-SqlCmd
- How to use SQLCMD commands in SSMS Query Editor
- Working with the SQL Server Command Line (sqlcmd)
- Discussing backup and restore automation using SQLCMD and SQL Server Agent
- How to use SQLCMD commands in SSMS Query Editor