2014-04-28 47 views
0

我在SQL Server 2005中使用CTE內部的表變量時出現以下錯誤。當我使用物理表時,它工作正常。「必須聲明表變量」錯誤與CTE

必須聲明表變量「@Employee」。
')'附近語法不正確。

代碼:

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 to use table variable in a dynamic sql statement?

+0

你拼錯@Emploee表頂部 - 嘗試添加缺少的y並重新運行 – AHiggins

+1

這個問題似乎是無關緊要的,因爲它太局部化了。 –

+2

這是由於我在桌面創建時出現錯字。我希望這個被刪除。 – Lijo

回答

3
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 @Emploee AS e   --<-- Wrong Spellings here 
    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 @Emploee e ON e.EmpId = em.Manager --<-- Mising @ sign here 
) 
SELECT * FROM EmployeeManagers 
+0

此外,您的兩位員工都沒有管理員,因此此查詢不會返回任何具有這兩條記錄的數據。 –

1

你有一個錯字:

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) 

應該@Employee