例如(真实的查询语句比这个复杂,用with用递归):
select *,DeptID + ParentDeptID tempID from Dept
where tempID > 2
提示:
消息 207,级别 16,状态 1,第 1 行
列名 'tempID' 无效。

打算先将查询结果作为集合再二次检索,
select * from
(
select *,DeptID + ParentDeptID tempID from Dept
) ttt
where tempID > 2结果:简单的查询语句没问题,可我的真实的查询语句里面有with关键字,一用就报错,
select * from
(
with cte as
(
select * from Dept
where 1 = 1
and DeptID = 1 union all select b.* from cte a,Dept b
where b.ParentDeptID = a.DeptID
)
select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
from cte
where 1 = 1
) temp
where childrenCounts > 0
消息 156,级别 15,状态 1,第 3 行
关键字 'with' 附近有语法错误。
消息 319,级别 15,状态 1,第 3 行
关键字 'with' 附近有语法错误。如果此语句是公用表表达式、xmlnamespaces 子句或者更改跟踪上下文子句,那么前一个语句必须以分号结尾。
消息 102,级别 15,状态 1,第 17 行
')' 附近有语法错误。

解决方案 »

  1.   

    ;with cte as
    (
    select * from Dept
    where 1 = 1
    and DeptID = 1union allselect b.* from cte a,Dept b
    where b.ParentDeptID = a.DeptID
    )
    select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
    from cte
    where 1 = 1
    select * from
    CTE where childrenCounts > 0
      

  2.   

    提示:
    (27 行受影响)
    消息 208,级别 16,状态 1,第 17 行
    对象名 'CTE' 无效。
      

  3.   

    select *
    from (select *,DeptID + ParentDeptID tempID from Dept)
    where tempID > 2這樣用或
    select *,DeptID + ParentDeptID tempID from Dept where DeptID + ParentDeptID> 2
      

  4.   

    ;with cte as
    (
    select * from Dept
    where 1 = 1
    and DeptID = 1union allselect b.* from cte a,Dept b
    where b.ParentDeptID = a.DeptID
    )
    select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
    from cte
    where (select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) > 0
      

  5.   


    ;with cte 
    as
    (
    select * from Dept
    where 1 = 1
    and DeptID = 1union allselect b.* from cte a,Dept b
    where b.ParentDeptID = a.DeptID
    ),Cte2
    AS
    (
    select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
    from cte
    )
    SELECT * FROM Cte2
    where childrenCounts > 0或;with cte 
    as
    (
    select * from Dept
    where 1 = 1
    and DeptID = 1union allselect b.* from cte a,Dept b
    where b.ParentDeptID = a.DeptID
    )SELECT *
    FROM 
    (
    select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
    from cte
    )
    SELECT * FROM Cte2
    where childrenCounts > 0
      

  6.   


    晕 你两个 CTE了CTE只能用一次 你可以这样 ;with cte as
    (
    select * from Dept
    where 1 = 1
    and DeptID = 1union allselect b.* from cte a,Dept b
    where b.ParentDeptID = a.DeptID
    )
    select *,(select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) childrenCounts
    from cte
    where (select COUNT(*) from cte tempCte where tempCte.parentDeptid = cte.deptid ) > 0