Articles → SQL SERVER → Execute TSQL Statements Using Sqlcmd Utility

Execute TSQL Statements Using Sqlcmd Utility






What Is Sqlcmd Utility?





Syntax


Sqlcmd –s <server_name> -i <script_file_name>



Creating Script Files






Use [Master] Go CREATE DATABASE gyansangrah;




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




Use [gyansangrah]
Go
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. Open the run popup (windows + R)
  2. Type cmd and press enter
  3. Command window open up
  4. Go to the path where the batch file is stored (using cd batch_file_path)
  5. Enter Script.bat and press enter



Output


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



Adding Output In A File





Syntax


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



Output


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


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


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



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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250