How to automatically execute SQL queries with a batch file (OSQL UTILITY)


Quick Demo

                       The osql utility 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.

Commonly Used Arguments:

-S (SQL Server\Instance name) Ex. -S myserver\SQLEXPRESS
-E (Uses a trusted connection instead of requesting a password)
-U (Login ID)
-P (Password)
-i (Input file) Ex. -i "c:\My Folder\MyScript.sql"
-o (Output file) Ex. -o "c:\My Folder\MyScriptLog.txt"

Example Syntax Usage:

osql -S .\sqlexpress -E -i "c:\defragIndexes.sql" -o "c:\defragIndexesLog.txt"
(This command would execute a SQL script on a local SQLExpress server using Windows Authentication)

osql -S mysql -U sqluser -P sqlpassword -i "c:\script.sql" -o "c:\outputLog.txt"
(This command would execute a SQL script on a SQL server using SQL authentication)

Note: osql no longer supports the ED and !! commands

No comments:
Write comments

Please do not enter spam links

Meet US

Services

More Services