Wednesday, November 6, 2013

Passing variables to .sql script file - using batch script and SQLCMD

1.Create  "Test.bat" file as given below script
 
Set DatabaseName=TestDB
sqlcmd -S "InstanceName" -i "C:\Createdb.sql"

2.--Createdb.sql
CREATE DATABASE $(DatabaseName) ON  PRIMARY
( NAME = N'TestDB', FILENAME = N'C:\DATA\TestDB11.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )
 LOG ON
( NAME = N'TestDB_log', FILENAME = N'C:\DATA\TestDB11_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
GO

3.Run the "Test.bat" file on command line.Then TestDB database will create it on SQL Server instance.

-------------
Other Examples:

USE AdventureWorks2012;
GO
SELECT x.$(ColumnName) FROM Person.Person x  WHERE c.BusinessEntityID < 5;

You can then specify the name of the column that you want returned by using the -v option:
sqlcmd -v ColumnName ="FirstName" -i c:\testscript.sql

To return a different column by using the same script, change the value of the ColumnName scripting variable.
sqlcmd -v ColumnName ="LastName" -i c:\testscript.sql


C:\>SET tablename=Person.Person
C:\>SET col1=FirstName
C:\>SET col2=LastName
C:\>SET title=Ms.
C:\>sqlcmd -d AdventureWorks2012
1> SELECT TOP 5 $(col1) + ' ' + $(col2) AS Name
2> FROM $(tablename)
3> WHERE Title ='$(title)'
4> GO