Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL: Global Script Variable?

I am making use of variables in my TSQL queries. As my script has grown, I have separated each part by GO, now the problem is I need access to variables at the top of my script.

How can I still access these variables?

Hopefully, this is something simple and straightforward.

Thanks all

like image 283
Abs Avatar asked Dec 29 '22 19:12

Abs


2 Answers

GO is used to separate batch of t-sql, Variables have local scope and are only visible within the batch or procedure where they are defined.

Your best best is probably to store the global stuff in a temp table, or if they are constant create a stored proc. to pull them at runtime.

like image 73
jfrobishow Avatar answered Jan 21 '23 15:01

jfrobishow


Bit late, but if you're using SSMS, you can put it in SQLCMD Mode and define variables that way. You can't change the variables once you've defined them, but it's still handy to know.

:setvar MyVariable "FooBar"

Select Foo from Bar where FooBar = '$(FooBar)'
GO
Insert Into Bar(FooBar) Values ('$(FooBar)')
GO
like image 38
Dan F Avatar answered Jan 21 '23 16:01

Dan F