How to automatically execute SQL queries with a batch file

Expand / Collapse

How to automatically execute SQL queries with a batch file

Article ID: 51069 - Last Review: December 14, 2010


The following article explains how to automatically execute SQL queries with the use of a batch file.


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:\defragIndexes.sql" -o "c:\defragIndexesLog.txt"
(This command would execute a SQL script on a SQL server using SQL authentication)

For more information about the OSQL Utility, see the following Microsoft article:


Once you have your batch file created with the "osql" command, you can use Windows Scheduled Tasks to automatically run this script.

  1. Open Control Panel=>Scheduled Tasks=>Add a Scheduled Task
  2. Browse to the batch file (Ex. c:\MyScripts\myscript.sql)
  3. Choose how often to run the task
  4. Choose the time to run the task
  5. Enter the Windows User account credentials


All CCM versions

Keywords: osql executing sql scripts automatically

Rate this Article:

Add Your Comments

Name: *
Email Address:
Web Address:
Verification Code:

Last Modified:Tuesday, December 14, 2010
Last Modified By: ademski
Rated 5 stars based on 1 vote
Article has been viewed 6,917 times.