I am getting following errors when I use a table variable inside a CTE in SQL Server 2005. When I use a physical table, it works fine.
Must declare the table variable "@Employee".
Incorrect syntax near ')'.
Code:
DECLARE @Emploee TABLE (EmpID INT, EmpName VARCHAR(50), Dept VARCHAR(5), Manager INT)
INSERT INTO @Emploee VALUES (1, 'A', NULL,NULL)
INSERT INTO @Emploee VALUES (2, 'B', 'D100',NULL)
;WITH EmployeeManagers AS
(
SELECT e.EmpId, e.EmpName, 1 AS Level
, e.Manager, e.EmpID CurrLevelEmpID, Cast(Null as VarChar(5)) Dept
FROM @Employee AS e
WHERE e.Manager IS NOT NULL
UNION ALL
SELECT em.EmpId, em.EmpName, Level + 1 AS Level
, e.Manager, e.EmpID CurrLevelEmpID, e.Dept Dept
FROM EmployeeManagers em
INNER JOIN Employee e ON e.EmpId = em.Manager
)
SELECT * FROM EmployeeManagers
How can we fix this error?
REFERENCE