Wednesday 3 October 2018

Execute SQL queries with a batch file or Command Line



Execute SQL queries with a batch file or Command Line

  • OSQL is a command line tool that allows you to issue commands to Microsoft SQL Server.
  • The OSQL allows you to enter Transact-SQL statements, system procedures, and script files.  This utility uses ODBC to communicate with the server.
  •  Once you have the OSQL command written, save the entire line into a file with a .bat extension.

Command Arguments:
-S (SQL Server\Instance name) Ex. -S nicsw5\SQL Express
-E (Uses a trusted connection instead of requesting a password)
-U (Login ID)
-P (Password)
-i (Input file) Ex. -i "c:\Folder\Script.sql"
-o (Output file) Ex. -o "c:\Folder\ScriptLog.txt"

Syntax :

  • Using Windows Authentication
osql -S nicsw5\SQL Express -E  -i "c:\Script_file.sql" -o "c:\Script_file_log.txt"

  •  Using SQL Authentication
osql -S nicsw5\SQL Express -U sql_user -P sql_password  -i "c:\Script_file.sql" -o "c:\Script_file_log.txt"


No comments:

Post a Comment

SQL Table : Change Row As Column and Group Them... ( Setting column values as column names in the SQL query result )

Setting column values as column names in the SQL query result Problem Statement : id col1 col2 1 Pending 30 1 Resolved 48 ...