I decided to write this article to respond to request of one of usergroup, which requested that they would like to learn sqlcmd 101.
SQL Server 2005 has introduced new utility sqlcmd to run ad hoc Transact-SQL statements and scripts from command prompt. T-SQL commands are entered in command prompt window and result is displayed in the same window, unless result set are sent to output files. sqlcmd can execute single T-SQL statement as well as batch file. sqlcmd utility can connect to earlier versions of SQL Server as well. The sqlcmd utility uses the OLE DB provider to execute T-SQL commands, whereas SQL ServerManagement studio uses .NET sqlclient to execute sqlcmd script, this can lead to different results in certain cases. (If you have example of this please let me know, I will post it here)
sqlcmd is enhenced version of the isql and osql and it provides way more functionality than other two options. In other words sqlcmd is better replacement of isql (which will be deprecated eventually) and osql (not included in SQL Server 2005 RTM). sqlcmd can work two modes – i) BATCH and ii) interactive modes.
Let us go over simple example of sqlcmd.
1) Step 1 : Go to Start >> Run >> Type “cmd” and press enter.
2) Step 2 : Type in command “sqlcmd” and press enter
3) Step 3 : Type following “USE AdventureWorks” command to switch database context to Adventureworks. Type “GO” after the batch to change the code. It will display the success message as “Changed database context to AdventureWorks”.
4) Step 4 : Now run any same query. Refer following image to see the query and its result.
5) Step 5 : Similar result we will get if the same query is ran in Query Editor in SSMS.
6) Type “exit” at any point if you do not want to continue working with sqlcmd.
The use of sqlcmd syntax is very easy however it this command can perform many powerful tasks. We will see that in future articles.
Reference : Pinal Dave (https://blog.sqlauthority.com)