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.
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.
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.
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.
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.
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)
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With