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.
Create table tblTest
Sno int identity,
set nocount on
Insert into tblTest (Fname) values ('alpha')
Insert into tblTest (Fname) values ('beta')
Create proc usp_GetAllTblTest
Select sno, fname from tblTest
Step 2: Create a batch file and call these .sql files in order.
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!