When I run this query in SQLCMD mode in SSMS 2017 and SQL Server DB. It works fine.
--SQLCMD mode
--DECLARE Global variables
:SETVAR daysBack -1
SELECT $(daysBack)
Result: -1
If I run only 1 line
SELECT $(daysBack)
in the same window on the same connection, or in another tab. I am getting error
fatal scripting error occurred. Variable daysBack is not defined.
Why I am getting error?
and how can I make my varibale Global, for example like
SELECT '$(COMPUTERNAME)'
I don't think you can. SQLCMD variables are a client tool trick, they don't really exist as a SQL Server concept.
The connection and server are not aware of their existence and the system doesn't persist knowledge of variables used in previous batches when you submit a new batch.
From sqlcmd - Use with Scripting Variables:
If more than one type of variable has the same name, the variable with the highest precedence is used.
System level environmental variables
User level environmental variables
Command shell (SET X=Y) set at command prompt before starting sqlcmd
sqlcmd-v X=Y
:Setvar X Y
Of these, the first three are effectively taken from when a particular process was launched, unless that process has specific tooling to allow environmental variable to be edited. Neither SSMS nor SQLCMD has such functionality so you cannot create a variable in these categories once the tool is already running.
The fourth is SQLCMD specific and has no equivalent in SSMS. Only the last one (using :setvar
) remains, and this does not create a "global" variable (which are in fact just the environmental variables and the SQLCMD built-in variables).