Dan Holmes (dan.holmes@routematch.com) writes:
> Now i am even more confused. Why does PRINT '$(filename)' and PRINT
> $(filename) produce different outputs? I get the value of @v in one and
> '@v' in the other? And if i can get $(filename) to print the value of
> @v why won't :r use that value when running?
It's nothing strange at all.
PRINT @v
prints the value of @v
PRINT '@v'
prints the string '@v'.
In SQLCMD you have defined the variable filename to have the value '@v'.
Then you say:
PRINT $(filename)
SQLCMD reads this line, and recognizes that $(filename) is an SQLCMD
variable, and replace it with its value before it sends the string to
SQL Server. SQL Server sees this:
DECLARE @v VARCHAR (MAX)
SET @v = 'c:\asdf.sql'
PRINT @v
It's important to understand that the order of execution here does not
agree with the text you see. You had:
DECLARE @v VARCHAR (MAX)
SET @v = 'c:\asdf.sql'
:setvar filename @v
PRINT $(filename)
But the actual execution order is:
:setvar filename @v
DECLARE @v VARCHAR (MAX)
SET @v = 'c:\asdf.sql'
PRINT $(filename)
And more in detail this happens:
1) SQLCMD parses the command text, looking for
a) go
b) it's own commands, those starting with :
c) Variables in $() to expand.
2) SQL performs commands and expansions as it finds them. When it reaches
go it sends the text to SQL Server.
3) SQL Server parses the batch, to check syntax and that.
4) SQL Server executes the batch.
5) SQLCMD gets the result back and prints the result.
--
Erland Sommarskog, SQL Server MVP, esquel.TakeThisOut@sommarskog.se
Links for SQL Server Books Online:
SQL 2008:
http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005:
http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000:
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx >> Stay informed about: sqlcmd mode and r command