Feb 20, 2011

How to pass variable to sql script from batch file?


How to pass variable to sql script from batch file?
1.       Create a Table called Employees
id int
fname varchar(50)
lname varchar(50)
dept varchar(10)

2.       Insert few records into it as
Id            fname                   lname                   dept
01           Mohd                    Irfan                      IT
02           Gaurav                  Thakur                  IT
03           Animesh              Mishra                  Security
04           Ashok                   Roy                        Admin
3.       Create the sql script as getEmployees.sql
use $(dbname)
select * from $(tablename)

4.       Create the runsqlscript.bat file for running the sql script as below.
sqlcmd -S %1 -i getEmployees.sql -v dbname = %2 tablename = %3 -o %4

5.       Run this command from cmd.
>runsqlscript.bat SQLServerName DBName Employees D:\EmployeesList.txt


SQL - Difference between CAST,CONVERT and PARSE

TODO---