Friday, February 9, 2018

Batch scripting - SQL Server - Execute all sql files from a folder

Description:
In my project code base, I have a structure for all database objects (stored procedure, functions, trigger etc.) as well as some upgrade scripts. Need a nice way to deploy all the database scripts rather manually execute one by one.

Environment information:
1. Windows Batch script
2. SQL Server 2014

Script:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@ECHO OFF
REM Database connection info
SET databaseName=db_name
SET databaseServer=db_server
SET databaseUserName=db_user
SET databasePassword=db_password

REM Location of scripts. Multiple folders can be specified by giving space in between and enclosed with quotation.
REM This script will go through only one level of sub folders and execute all .sql files
SET scriptLocation="location1" "location2"



REM -----------------------------------------------------------
REM - Logic 
REM -----------------------------------------------------------

SET initialLocation=%cd%

FOR %%e IN (%scriptLocation%) DO (
 @ECHO ------------------------
 @ECHO %%e
 @ECHO ------------------------
 IF EXIST %%e (
  CALL :executeScripts %%e
 
  FOR /D %%i IN (%%e\*) DO (
   @ECHO ------------------------
   @ECHO %%i
   @ECHO ------------------------
   CALL :executeScripts "%%i"
   
  )
 ) 
)

CD %initialLocation%
PAUSE


:: This function execute all the scripts from given path
:executeScripts
FOR %%G IN (%1\*.sql) DO (
 @ECHO %%~nxG  
 sqlcmd /S %databaseServer%  /d %databaseName%  -U %databaseUserName%  -P %databasePassword% -i"%%G"
)
EXIT /B 0

No comments: