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

ぃ、小莉子 提交于 2019-11-27 08:27:48

问题


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?


回答1:


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




回答2:


This is because the INNER JOIN expects the parameters are variables. This should work:

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

insert into @_FileIDs
    select 73, 'abc'

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

select
    *
from
    @_Errors AS tblErrors
    inner join @_FileIDs AS tblFileID
    on tblErrors.ID = tblFileID.ID


来源:https://stackoverflow.com/questions/13802703/t-sql-how-to-join-variable-tables-another-try

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!