Home > General DBA, SQL Server, osql > How to script osql to run scripts using batch file?

How to script osql to run scripts using batch file?

Using batch file one can automate running of scripts in osql.

Script that the main script which loops through file names in scripts.txt and calls runone.bat
C:> type runscript.bat
FOR /f %%a in (scripts.txt) do call runone.bat %%a

Script that runs one SQL script at a time, it connects using trusted account and dumps the output to scriptname.txt.out. If the script generates an error it returns a status and prints a message that error was encountered.
c:> type runone.bat
osql -E -b -d databasename -i %1 -o %1.out
@if errorlevel 1 @echo “there was an error see %1.out”

Input file list of scripts
c:> type scripts.txt
script1.sql
script2.sql
script3.sql

Sample output:

c:> .\runscript.bat

c:> FOR /F %a in (scripts.txt) do call runone.bat %a

c:> call runone.bat script1.sql

c:> osql -E -b -d msdb -i script1.sql -o script1.sql.out

c:> pause
Press any key to continue . . .

c:> call runone.bat script2.sql

c:> osql -E -b -d msdb -i script2.sql -o script2.sql.out
“there was an error see script2.sql.out”

c:> pause
Press any key to continue . . .

c:> call runone.bat script3.sql

c:> osql -E -b -d msdb -i script3.sql -o script3.sql.out
“there was an error see script3.sql.out”

c:> pause
Press any key to continue . . .

Categories: General DBA, SQL Server, osql Tags:
  1. No comments yet.
  1. No trackbacks yet.
6 visitors online now
6 guests, 0 members
Max visitors today: 11 at 12:30 pm UTC
This month: 11 at 09-07-2010 12:30 pm UTC
This year: 62 at 07-28-2010 05:49 pm UTC
All time: 62 at 07-28-2010 05:49 pm UTC