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


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