SQL Server CTE hierarchy?

£可爱£侵袭症+ 提交于 2019-12-22 11:28:24

问题


I have a table which has hierarchy in it.

Lets start with Id = 5; this is the child. (a given start parameter - from user)

Algorithm:

  • give me the first value which you have encountered for id = 5
  • if you haven't found value for id = 5, go to its parent and give me his id
  • if this parent also doesn't have a value - go to its parent ... etc (until parent has no parent - parentId = 0)

p.s. the result here should be 7.

if 7 value was empty so : 9

end if 9 was also empty so : 1

I'm trying to do this with CTE but no success..

p.s. I want a solution with CTE. :)

What I have tried (don't even look at it - it doesn't work):

WITH cte AS (
SELECT  
       id,VALUE,parentid

  FROM [test].[dbo].[tmp]   WHERE id=5
  UNION ALL

  SELECT  
      id,VALUE,parentid
  FROM  [tmp]   WHERE parentId=cte.parentId ) //ERROR : The multi-part identifier "cte.parentId" could not be bound.
  SELECT * FROM cte

回答1:


You need to join in your cte:

with cte as (
select
    id,
    value,
    parentid
from
    [tmp]
where 
    id=5
union all
select
    tmp.id,
    coalesce(cte.value, tmp.value) as value,
    tmp.parentid
from  
    [tmp]
    inner join cte on
        tmp.id = cte.parentId
)
select
    max(value) as value
from
    cte

If you're going to reference a table, you need to make sure that you've joined it somewhere in your from clause. In this case, you hadn't, which is why it was throwing the error.



来源:https://stackoverflow.com/questions/8749502/sql-server-cte-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!