Thursday, March 16, 2006

SQL 2005 - SQLCMD command-line tool

SQLCMD command-line tool allows you to pass variables from the command line into the SQL Script itself. In SQL 2005 now, you’ll can able to use SQLCMD as below example:
- Database build scripts where you need to pass values specific to a certain environment. - Hot fixes and patches.
- Any scenario where use of stored procedures (with it’s built-in parameters) is not an option and you must rely on a SQL script.
In this example SQLCMDTest.SQL [NOTE: That you must delimit character strings with a single quote]
declare @DaysToAdd datetime,
@MyString varchar(32)

SELECT @DaysToAdd =$(daystoAdd),
@MyString='$(mystring)'

SELECT GETDATE()+@DaysToAdd,
@MyString

Then, you call the SQL Script passing in the values as:
SQLCMD -b -w4000 -l10 -E -i"SQLCMDTest.sql" -v daystoAdd="10" -v mystring="CeltoGrass"

No comments: