PowerUser
PowerUser

Reputation: 11791

Why did my query forget my variable declaration?

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:

  1. There are no typos in the variable.
  2. I don't see any other errors. I can comment out this portion of the query and it runs fine.
  3. If I put my Declaration statement immediately above the 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

Answers (1)

dpw
dpw

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

Related Questions