这是我的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'.
我无法发现错误。所以请任何人都有很多,并帮助我解决它。感谢名单。
答案 0 :(得分: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
答案 1 :(得分: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
OR
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