Pages

Wednesday, February 12, 2014

Batch script by example. Read parameters from file, loop on parameters, pass parameters to another bat file, which calls sql file

The Flow
Need to run a SQL on several remote databases, and report the results.
The hierarchy is Main.bat => Version.bat => Product.bat => PROD_X_Generate_sql.bat => Generates sql file.
The generated file is zipped, and moved to output folder.


The files:
main.bat

run_sql.bat
sql_statement.sql
parameters.ini

parameters.ini
Lists all databases we need to connect to.

main.bat
- Read ini parameters file

- Call run_sql.bat with value read from parameters file, and report file name as parameters.

run_sql.bat
- Call sql_statement.sql with received parameters.

sql_statement.sql

Execute SQL statment, with received parameters and spool to a file.

===========================
parameters.ini
===========================
userA/passA@connect_strA

userB/passB@connect_strB

===========================
main.bat
===========================
ECHO OFF
setlocal
cls

SET inifile=db_list.ini
SET REFRESH_LOG=gates_refresh_log_stats.txt
SET TEMP_REFRESH_LOG=temp_gates_refresh_log_stats.txt

ECHO.
ECHO =============================================
ECHO main is starting
ECHO This Program read entries from file %inifile% and report results to %REFRESH_LOG%
ECHO =============================================
ECHO.

ECHO. 2>%TEMP_REFRESH_LOG%
ECHO. 2>%REFRESH_LOG%

FOR /F "tokens=*" %%i IN (%inifile%) DO (
    ECHO handling %%i
    call run_sql.bat %TEMP_REFRESH_LOG% %%i
    TYPE %TEMP_REFRESH_LOG% >> %REFRESH_LOG%
ECHO.
)

ECHO.
ECHO =============================================
ECHO main has finished
ECHO =============================================


===========================
run_sql.bat
===========================

SET spool_to_file=%1
SET db_name=%2
sqlplus -s %db_name% @refresh_log_sql %spool_to_file% %db_name%

===========================
sql_statement.sql
===========================
SET TERMOUT ON
SET SHOW OFF
SET VERIFY OFF 
SET HEAD ON
SET LINE 500
SET FEEDBACK OFF
SET PAGES 500
SET TRIMS ON

SPOOL &&1

SELECT '&&2' AS GATE_NAME, COUNT(*) AS REFRESH_LOG_ENTRIES FROM REFRESH_LOG;
SPOOL OFF
EXIT

/

No comments:

Post a Comment