“必须声明表变量”CTE出错

时间:2014-04-28 19:27:56

标签: sql sql-server

当我在SQL Server 2005中的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?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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