MS SQL Batch Scripts To Run

This batch script is designed to run a series of sql script files in default order of a directory.  In this case this batch file called for example: run_scripts.bat

Is in the same folder as the *.sql files and they are most likely ordered by name something like this

  • 1_first_script.sql
  • 2_second_script.sql
@ECHO OFF

REM Could be different need better way to find sqlcmd
REM SET SQLCMD="C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\SQLCMD.EXE"
SET SQLCMD="SQLCMD.EXE"
SET SQLFILEPATH="."
SET SERVER="localhost"
SET DB="my_local_database"
SET OUTPUT="sql_log_%time::=_%.txt"

CD %SQLFILEPATH%
ECHO %date% %time% > %OUTPUT%

for %%f in (*.sql) do (
	ECHO Running script %%f
	%SQLCMD% -S %SERVER% -d %DB% -i %%~f >> %OUTPUT%
)

This will produce a log file in the same directory named something like this sql_log_ 9_14_58.79.txt