I am making use of variables in my TSQL queries. As my script has grown, I have开发者_StackOverflow中文版 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
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.
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
Had a similar problem.
My solution:
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
精彩评论