Monday, February 18, 2019

SQL - Run sql from a batch file

https://docs.microsoft.com/en-us/sql/ssms/scripting/sqlcmd-run-transact-sql-script-files?view=sql-server-2017


  • Create text file with sql script named myScript.sql
  • create batch file with following command
    • sqlcmd -S myServer\instanceName -i C:\myScript.sql
  • Run batch file

Full script with logging

https://www.sqlservercentral.com/forums/topic/batch-file-to-run-sql-scripts
@ECHO OFF
SET SQLCMD="C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
SET PATH="C:\path\to\sql\files\"
SET SERVER="Server\Instance"
SET DB="Database"
SET LOGIN="sa"
SET PASSWORD="pass"
SET OUTPUT="C:\OutputLog.txt"
CD %PATH%
ECHO %date% %time% > %OUTPUT%
for %%f in (*.sql) do (
%SQLCMD% -S %SERVER% -d %DB% -U %LOGIN% -P %PASSWORD% -i %%~f >> %OUTPUT%
)

No comments:

Post a Comment