Articles → SQL SERVER → Execute TSQL Statements Using Sqlcmd Utility

Execute TSQL Statements Using Sqlcmd Utility

What Is Sqlcmd Utility?


Sqlcmd –s <server_name> -i <script_file_name>

Creating Script Files

Use [Master] Go CREATE DATABASE gyansangrah;

Use [gyansangrah] 
  Create table Test (
  TestId Int Identity(1, 1), 
  TestName varchar(50)

Use [gyansangrah]
Insert into Test values('Test1')

Create A Batch File

sqlcmd -S .\SQLserver  -i C:\temp\scripts\create_database.sql

sqlcmd -S .\SQLserver -i C:\temp\scripts\create_table_Test.sql 

sqlcmd -S .\SQLserver  -i C:\temp\scripts\Insert_Into_Test.sql 

Run The Batch File

  1. Go to run (windows + R)
  2. Type cmd and press enter
  3. Command window open up
  4. Go to the path where batch file is stored (using cd batch_file_path)
  5. Enter Script.bat and press enter


Picture showing the database and table created after the batch file is executed

Click to Enlarge

Adding Output In A File


Sqlcmd –s <server_name> -i <script_file_name> -o <output_file_path>

sqlcmd -S .\SQLserver -i C:\temp\scripts\create_database.sql -o C:\temp\scripts\create_database.txt

sqlcmd -S .\SQLserver -i C:\temp\scripts\create_table_Test.sql -o C:\temp\scripts\create_table_Test.txt

sqlcmd -S .\SQLserver -i C:\temp\scripts\Insert_Into_Test.sql -o C:\temp\scripts\Insert_Into_Test.txt


Picture showing adding the output of the query execution to the file

Click to Enlarge

Posted By  -  Karan Gupta
Posted On  -  Tuesday, July 12, 2016
Updated On  -  Friday, September 23, 2016


Your Email Id  
Query/FeedbackCharacters remaining 250