Reputation: 11791
I'd like to declare a variable at the top of my query for ease of use. Later, I'll use it after a number of other commands have already run. Here's what I instinctively wrote:
Declare @DoThatThing varchar(1)
Set @DoThatThing='Y'
BlahBlahBlah (Updates, Inserts, Selects, etc. A few Go commands too)
if @DoThatThing='Y' begin
Do More Stuff
end
However on my if @DoThatThing='Y' begin
line, I'm getting the error Must declare the scalar variable "@DoThatThing". Some other notes:
if
statement, then it runs fine. That makes me suspect one of my other commands is somehow clearing the variable out of memory.Does anyone know why my code can't run as intended?
Upvotes: 0
Views: 115
Reputation: 1586
If your script had "a few GO commands too" in it, then you've started a batch after each GO. Your variable declaration is only valid for the current batch.
Upvotes: 2