How to run SQL Scripts using Command Prompt or in a batch file


How to run sql script using command prompt
or
How to deploy database in production environment
or 
How to create database using batch file
or 
How to run sql scripts stored in a folder
or 
Automating Database Creation
or
How to call various SQL Scripts from Master SQL Script (Master - Child Scripts)

I have came across various clients, where they would not be have SQL Server Management Studio installed on their production box and if you want to run SQL Scripts using command prompt then you can follow below example

Step1 - Create a batch file and when you execute this batch file then it will run create_db.sql file against Master database which is stored in C:\Mihir\Scripts folder and creates an empty database

SQLCMD -E -dmaster -i C:\Scripts\create_db.sql

PAUSE

Step2 - Here I have created a Master SQL Script (Create_DB.sql), which will call various child Scripts

/* BUILD A DATABASE */

-- This is the Master Script
SET NOCOUNT ON
GO

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

:On Error exit

:r c:\Scripts\CREATE_TABLES.sql
:r c:\Scripts\TABLE_INSERTS.sql
:r c:\Scripts\CREATE_INDEXES.sql
:r c:\Scripts\CREATE_PROCEDURES.sql

PRINT 'DATABASE CREATE IS COMPLETE'
GO




Step3 - Now various child Scripts will be executed which will create required database objects such as creating tables, inserting records in to required tables, creating Indexes and stored procedures


And once all the scripts are run successfully, you will get Database Create is Complete and you can verify the database creation.

Source File as attached
https://drive.google.com/file/d/0B40RqOcLP1O4VTRtQTdCNmtmZ1U/edit?usp=sharing


Comments

Popular posts from this blog

Calculating Age of the person in T-SQL

How to Troubleshoot Subscription issue in Reporting Services