SQL Server: table variable used in a inner join

前端 未结 5 934
无人及你
无人及你 2021-01-01 12:18

What is the problem with following SQL. Can table variable not be used in JOIN clause?

Error msg is of \"Msg 170, Level 15, State 1, Line 8 Line 8:

相关标签:
5条回答
  • 2021-01-01 12:43

    Change your last statement to:

    UPDATE t1, temp
    SET t1.SportName = temp._SportName
    FROM tblSport AS t1
    INNER JOIN @t AS temp
        ON t1.Lang = temp._Lang
    

    (need to check exact syntax)

    0 讨论(0)
  • 2021-01-01 13:02

    don't forget use alias for variable tables

    Declare @t TABLE (
        _SportName  varchar(50),
        _Lang       varchar(3)
    )
    
    insert @t VALUES('Basketball', 'ENG') -- ENG
    
    UPDATE t1 
    SET 
        t1.SportName = t2._SportName
    FROM tblSport t1 INNER JOIN
        @t as t2  ON (t1.Lang = t2._Lang)
    
    0 讨论(0)
  • 2021-01-01 13:03

    Apart from the t1 alias being in the wrong place, nobody else mentioned using square brackets around the table variable, instead of an alias. Changing the update statement to the following will work too:

    UPDATE t1
    SET
        t1.SportName = [@t]._SportName
    FROM
        @t INNER JOIN tblSport t1 ON t1.Lang = [@t]._Lang
    

    [Tested on SQL Server 2005.]

    0 讨论(0)
  • 2021-01-01 13:06

    Justin's answer is correct syntactically - you need to assign an alias to the temp table (same for table type variables in 2008).

    However, be aware that neither table variables nor table-type variables have any statistics associated with them, and therefore can lead the query optimiser to make very dubious choices with regard to execution plans (because it will always estimate that the table variable contains 1 row - and therefore usually chooses nested loops as a join operator).

    0 讨论(0)
  • 2021-01-01 13:09

    Your alias t1 is in the wrong place

    UPDATE
        t1 
    SET 
        SportName = @t._SportName
    FROM 
        @t INNER JOIN tblSport t1 ON (t1.Lang = @t._Lang)
    
    0 讨论(0)
提交回复
热议问题