-1

这是我的 CTE - 它导致错误。帮我找出错误

CREATE TABLE [dbo].[myEmpTab](
[EMPNO] [int] NULL,
[ENAME] [varchar](10)  NULL,
[JOB] [varchar](20)  NULL,
[MGR] [int] NULL,
[HIREDATE] [datetime] NULL,
[SAL] [int] NULL
) ON [PRIMARY]

;
WITH MyCTE AS 
( 
  SELECT EMPNO, EName, Null as MGR, NULL as ManagerName
  FROM myEmpTab
  WHERE MGR IS NULL
  UNION ALL
  SELECT  EMPNO, EName, MGR, MyCTE.EName
  FROM myEmpTab
  INNER JOIN MyCTE ON myEmpTab.MGR = MyCTE.EMPNO
  WHERE myEmpTab.MGR IS NOT NULL 
)
SELECT * FROM MyCTE

当我执行 sql 时,我会收到类似的错误

Msg 209, Level 16, State 1, Line 8
Ambiguous column name 'EMPNO'.
Msg 209, Level 16, State 1, Line 8
Ambiguous column name 'EName'.
Msg 209, Level 16, State 1, Line 8
Ambiguous column name 'MGR'.

我无法捕捉到错误。所以请任何人有很多,并帮助我解决它。谢谢。

4

2 回答 2

1

在您的编辑之后,您可能需要类似的东西

;WITH MyCTE AS 
( 
  SELECT EMPNO, EName, NULL as MGR, CAST(Null AS  VARCHAR(10)) as ManagerName
  FROM myEmpTab
  WHERE MGR IS NULL
  UNION ALL
  SELECT  myEmpTab.EMPNO, myEmpTab.EName, MyCTE.MGR, MyCTE.EName
  FROM myEmpTab
  INNER JOIN MyCTE ON myEmpTab.MGR = MyCTE.EMPNO
  WHERE myEmpTab.MGR IS NOT NULL 
)
SELECT * FROM MyCTE
于 2012-09-17T11:54:20.103 回答
0

我认为您不能在其内部引用 CTE。试试这个

WITH MyCTE AS 
( 
SELECT EMPNO, EName, MGR, Sal
FROM myEmpTab
WHERE MGR IS NULL
)

SELECT EMPNO, EName, MGR, Sal FROM MyCTE

UNION ALL

SELECT  e.EMPNO, e.EName, e.MGR, MyCTE.EName
FROM myEmpTab e
INNER JOIN MyCTE ON e.MGR = MyCTE.EMPNO
WHERE e.MGR IS NOT NULL 

或者

WITH MyCTE AS 
( 
    SELECT EMPNO, EName, MGR, Sal
    FROM myEmpTab
    WHERE MGR IS NULL
),
MyCTE2 as
(
    SELECT EMPNO, EName, MGR, Sal FROM MyCTE

    UNION ALL

    SELECT  e.EMPNO, e.EName, e.MGR, MyCTE.EName
    FROM myEmpTab e
    INNER JOIN MyCTE ON e.MGR = MyCTE.EMPNO
    WHERE e.MGR IS NOT NULL 
)
SELECT * FROM MyCTE2
于 2012-09-17T09:32:00.350 回答