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