Search code examples
sql-servert-sqltable-variable

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


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?


Solution

  • 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.