Is there a way to persist a variable across a go?
Use SQL Server's temporary tables to maintain a variable value past the GO
boundary. Here's how you'd do it:
Through this method, variables persist beyond GO
, countering the limited scope of @variable
.
Deconstructing "GO"-ing beyond
Spot unnecessary "GO" commands and remove them
A method to consider before introducing workarounds is reviewing your script to eliminate redundant GO
s. A simple restructure can sometimes help maintain the variable's scope.
Variables and stored procedures - A friendship story
When playing with stored procedures or user-defined functions, pass variables as parameters. Thus, they persist through GO
via provided parameters:
SQLCMD and variable - The odd couple
While running scripts in SQLCMD mode, you can use :setvar
to declare variables. These can then be accessed via $(VARIABLE_NAME)
, skirting GO
:
One caveat - dynamically switching databases with USE @variable
is off the table—you'll need to go the literal database name route.
SQL's unique quirks and practices
SQL Server has its own peculiarities. The GO
statement is your batch terminator, meaning a SQL Server variable has a batch-limited scope. Nevertheless, sometimes you're required to have variables persist beyond one batch.
Workarounds for syntax hitches
Directly using USE @bob
doesn't exactly fly; however, for such cases, we construct dynamic SQL as a workaround:
Exercise caution—dynamic SQL brings its own set of security considerations and best practices.
Was this article helpful?