Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: table variable used in a inner join

Tags:

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: Incorrect syntax near 't1'."

Declare @t TABLE (     _SportName  varchar(50),     _Lang       varchar(3) )  insert @t VALUES('Basketball', 'ENG') -- ENG  UPDATE tblSport t1  SET      t1.SportName = @t._SportName FROM      @t INNER JOIN tblSport ON (t1.Lang = @t._Lang) 

Thanks.

like image 703
Ricky Avatar asked Feb 03 '10 03:02

Ricky


People also ask

Can we use table variable in join?

It turns out that this is entirely possible, as long as you are not passing in a value or variable to the table function as parameter, but NOT a column from the joining table.

Can we use table variable in function in SQL Server?

Table variables can be declared within batches, functions, and stored procedures, and table variables automatically go out of scope when the declaration batch, function, or stored procedure goes out of scope. Within their scope, table variables can be used in SELECT, INSERT, UPDATE, and DELETE statements.

What is the use of table variable in SQL Server?

The table variable is a special type of the local variable that helps to store data temporarily, similar to the temp table in SQL Server. In fact, the table variable provides all the properties of the local variable, but the local variables have some limitations, unlike temp or regular tables.

Do we need to drop table variable in SQL Server?

We do not require dropping the table variable. As mentioned earlier, the scope of the table variable is within the batch. The scope of it lasts at the end of the batch or procedure.


2 Answers

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)

like image 133
Justin Niessner Avatar answered Dec 16 '22 15:12

Justin Niessner


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

like image 43
takrl Avatar answered Dec 16 '22 15:12

takrl