Search code examples
sqlt-sqlsql-server-2008-express

T-SQL: How to join @variable tables (another try)


I know, this is a duplicate question of this question. But i encountered the same problem and maybe i can provide some more available informations.

If i try out the following example query:

DECLARE @_Files TABLE (ID INT, Filename VARCHAR(MAX));
DECLARE @_Errors TABLE (ID INT, Label VARCHAR(MAX), Value VARCHAR(MAX));

insert into @_Files
    select 73, 'abc'

insert into @_Errors
    select 73, 'Some label name', 'Just a value'

select
    *
from
    @_Errors 
    inner join @_Files
    on @_Errors.ID = @_Files.ID

I got the error message:

The @_Errors-scalar variable must be declared.
The @_Files-scalar variable must be declared.

I'm using SQL-Server 2008 R2 Express and it is running at compatibility level 100. So any ideas why i get this error?


Solution

  • Either give them an alias that you then refer to in the JOIN or use square brackets. The below mixes both possibilities.

    SELECT *
    FROM   @_Errors Errors
           INNER JOIN @_Files 
             ON Errors.ID  = [@_Files].ID 
    

    There is a Connect Item discussing this issue here