Saturday, 21 March 2015

Pin It

Widgets

Run multiple SQL scripts in order using a batch file

Suppose, we have to run following sql files in the order:


1) CREATE_TABLES.sql
2) TABLE_INSERTS.sql
3) CREATE_INDEXES.sql
4) CREATE_PROCEDURES.sql

and suppose they are all present in the directory:
C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck


Now, create a script say CREATE_DB.sql 
SET NOCOUNT ON
GO

PRINT 'CREATING DATABASE'
IF EXISTS (SELECT 1 FROM SYS.DATABASES WHERE NAME = 'HELLODB')
DROP DATABASE HELLODB
GO
CREATE DATABASE HELLODB
GO

USE HELLODB
GO
:On Error exit

:r "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\CREATE_TABLES.sql"
:r "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\TABLE_INSERTS.sql"
:r "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\CREATE_INDEXES.sql"
:r "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\CREATE_PROCEDURES.sql"

PRINT 'DATABASE CREATE IS COMPLETE'
GO


If HELLODB already exists and you don't want to drop it, then remove the highlighted code above.

Now, create a new file, add the following code and save as demo.bat:

if HELLODB already exists:
SQLCMD -E -d HELLODB -i "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\create_db.sql"
PAUSE

if HELLODB does not exist:
SQLCMD -E -d master -i "C:\Users\Arjun\Documents\SQL Server Management Studio\BATCheck\create_db.sql"
PAUSE

Now, double click the demo.bat file and all the sql scripts will get executed.

No comments: