Wednesday, November 14, 2007

SQLCMD -- Part IX (Batch files)

Using SQLCMD to execute script files easily in different environments

Assume we have few script files (.sql) which needs to be run in multiple SQL Servers. Hope you would accept that's real pain to connect into different servers from SQL Management Studio and then execute the scripts one after the other.

One of the easiest ways of doing it is by making use of the SQLCMD utility of SQL Server 2005.

Step 1: Lets create few dummy script files for demo purpose.

File1: 01TableCreation.sql

Create table tblTest
(
Sno int identity,
FName varchar(20)
)
Go

File2: 02InsertRecords.sql

set nocount on

Insert into tblTest (Fname) values ('alpha')
Insert into tblTest (Fname) values ('beta')


File3: 03StoredProcedures.sql

Create proc usp_GetAllTblTest
as
Select sno, fname from tblTest
go


Step 2: Create a batch file and call these .sql files in order.

File4: DBInstallationScripts.bat

sqlcmd -U %1 -P %2 -S %3 -d %4 -i "C:\Vadivel\SQL Related\Scripts\sqlcmd1\01TableCreation.sql"
sqlcmd -U %1 -P %2 -S %3 -d %4 -i "C:\Vadivel\SQL Related\Scripts\sqlcmd1\02InsertRecords.sql"
sqlcmd -U %1 -P %2 -S %3 -d %4 -i "C:\Vadivel\SQL Related\Scripts\sqlcmd1\03StoredProcedures.sql"


Step 3: Execute the batch file

From the command prompt (Start >> Run >> Cmd) do the following:

c:> DBInstallationScripts DBUserName DBPassword DBServerName Databasename

Please note we are passing the database username, password, servername and the database to which we need to connect from the batch file. That way it would replace %1, %2, %3 and %4 in the batch file while executing.



So this way, same set of scripts can be executed in different environments like 'Development', 'Testing', 'Production' etc., with ease.

Hope this helps!

3 comments:

CodeSlammer said...

Very helpful post - nice and straightforward. Do you have any tricks on how to make this work using a UNC path on a network? I am thinkng of mapping a drive in a setup scripts or something like that.

Anonymous said...

Isn't there a way to invoke the SQLCMD just once..

SQLCMD [connect options] motherscript.sql

where motherscript.sql will have
@child1SQL
@child2SQL
----


- Deb

Sher said...

Hi
I have a stored proc - sql 2005. I want to call the stored proc in a batch file. Please help with the syntax for the batch file.