Table variable error: Must declare the scalar variable "@temp"

objectWithoutClass picture objectWithoutClass · Aug 1, 2013 · Viewed 167.5k times · Source

I am trying to achieve:

declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table

SELECT * FROM @TEMP 
WHERE @TEMP.ID  = 1        <--- ERROR AT @TEMP.ID

But I'm getting the following error:

Must declare the scalar variable "@temp".

What am I doing wrong?

Answer

Gordon Linoff picture Gordon Linoff · Aug 1, 2013

A table alias cannot start with a @. So, give @Temp another alias (or leave out the two-part naming altogether):

SELECT *
FROM @TEMP t
WHERE t.ID = 1;

Also, a single equals sign is traditionally used in SQL for a comparison.