TSQL: Script global variable?

I use variables in my TSQL queries. As my script grew, I divided each part into GO , now the problem is that I need access to the variables at the top of my script.

How can I access these variables?

I hope this is something simple and straightforward.

Thank you all

+4
source share
3 answers

GO is used to split the t-sql batch; variables have a local scope and are visible only in the batch or procedure where they are defined.

It is probably best to store global data in a temporary table, or if it constantly creates a stored procedure. to pull them out at runtime.

+8
source

The bit is late, but if you use SSMS, you can put it in SQLCMD mode and define the variables this way. You cannot change variables as soon as you define them, but it is still useful to know.

 :setvar MyVariable "FooBar" Select Foo from Bar where FooBar = '$(FooBar)' GO Insert Into Bar(FooBar) Values ('$(FooBar)') GO 
+2
source

Had a similar problem.

My decision:

 IF OBJECT_ID('tempdb..#range') IS NOT NULL DROP TABLE #range GO SELECT '06/01/15' STARTING_DATE, '06/30/15' ENDING_DATE INTO #range GO SELECT f.* FROM foo f INNER JOIN #range r ON f.date_field BETWEEN r.starting_date AND r.ending_date GO SELECT b.* FROM bar b INNER JOIN #range r ON b.date_field BETWEEN r.starting_date AND r.ending_date GO IF OBJECT_ID('tempdb..#range') IS NOT NULL DROP TABLE #range GO 
0
source

Source: https://habr.com/ru/post/1307724/


All Articles