Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a table variable in SQL Server

Tags:

sql

sql-server

I have designed a small query for table variable. This is the code:

DECLARE @TESTTABLE TABLE (ID INT, NAME VARCHAR(40))

INSERT INTO @TESTTABLE 
VALUES (1, 'WALLEY'), (2, 'BARRY'), (3, 'TIM'),
       (4, 'DICK'), (5, 'BRUCE')

My question is SQL allows use of alias for table variable like in the below query.

SELECT * 
FROM @TESTTABLE t 
INNER JOIN EMPLOYEE_DETAILS ON t.ID = BusinessEntityID

But you cannot use the actual table variable name like below:

SELECT * 
FROM @TESTTABLE 
INNER JOIN EMPLOYEE_DETAILS ON @TESTTABLE.ID = BusinessEntityID

The above query shows an error.

Does anyone have an answer for this? Would be really helpful.

like image 683
Tushal Singh Avatar asked Mar 05 '23 12:03

Tushal Singh


2 Answers

In T-SQL, you need to use aliases when joining variable tables.

Reference : https://odetocode.com/articles/365.aspx (see section : Restrictions)

It should give you something like this :

SELECT * 
FROM @TESTTABLE tt 
INNER JOIN EMPLOYEE_DETAILS emp_d 
ON tt.ID = emp_d.BusinessEntityID
like image 177
Dessma Avatar answered Mar 15 '23 11:03

Dessma


Use "[..]" to quote the table variable's name. This works for me:

SELECT * 
FROM @TESTTABLE INNER JOIN 
     EMPLOYEE_DETAILS
     ON [@TESTTABLE].ID = BusinessEntityID

That said, I would probably prefer to use an alias, or just use a CTE and forego the table variable altogether.

like image 20
RBarryYoung Avatar answered Mar 15 '23 10:03

RBarryYoung