Declaring Global Variables in SQL Server
Problem:
A developer encounters an error when attempting to declare and use global variables across different databases within a single Transact-SQL script. The error indicates that the scalar variable "@GLOBAL_VAR_2" is not declared.
Solution:
Transact-SQL does not support the concept of global variables. However, there is a workaround using the SQLCMD tool or the SQLCMD mode of SSMS.
In SQLCMD or SQLCMD mode, you can define tool-specific variables using the ":setvar" command:
:setvar myvar 10
Once defined, these variables can be used within the script using the "$(variable-name)" syntax:
$(myvar)
To use SQLCMD mode in SSMS, select the "Start SQLCMD mode (Ctrl 1)" option from the Query menu.
The above is the detailed content of How Can I Use Global Variables Across Different SQL Server Databases?. For more information, please follow other related articles on the PHP Chinese website!