Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 709
objectWithoutClass Avatar asked Aug 01 '13 13:08

objectWithoutClass


People also ask

How do you resolve must declare the scalar variable?

– Solving Local Declared Variable in Dynamic SQL Statement You can resolve that issue in two ways: Insert the code that uses the variable in the dynamic SQL. Insert the value in a temporary table (table will be seen outside the scope) and use it outside dynamic – execute SELECT against the temporary table.

What does must declare the scalar variable mean in SQL?

A scalar variable declaration specifies the name and data type of the variable and allocates storage for it. The declaration can also assign an initial value and impose the NOT NULL constraint. You reference a scalar variable by its name.


1 Answers

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.

like image 91
Gordon Linoff Avatar answered Sep 17 '22 10:09

Gordon Linoff