sql server 2005 - Recursive CTE with non-numeric hierarchy data -


i have (simplified) table:

orgname  |  hierarchy ---------|------------ org1     | org2     | aa org3     | ab org4     | aba 

an organization child of organization if:

  1. the child's length 1 greater parent
  2. the parent's hierarchy code matches first len(parent.hierarchy) of child's code

so in table:

  1. org2 , org3 children org1
  2. org4 child of org3 , grandchild org1

my question how write recursive hierarchy find descendants of particular organization? of cte examples i've read have numeric conditions of join (like employee.managerid = cte.empid). here's have far:

delcare @search varchare = 'a' org_cte (orgname, hlevel, recursionlevel)   (select o.orgname, o.hierarchy, 0 recursionlevel    orgtable o    o.hierarchy = @search    union    select o.orgname, o.hierarchy, recursionlevel + 1    orgtable o    inner join org_cte    on ???)  select orgname, hlevel, recursion org_cte 

i'm new cte, help!

edit:

this should it. overlooked start recursion level 0 , same level needs excluded:

with org_cte (orgname, hlevel, recursionlevel) (    select o.orgname, o.hierarchy, 1 recursionlevel    orgtable o    o.hierarchy = 'a'    union    select o.orgname, o.hierarchy, recursionlevel + 1    orgtable o    join org_cte      on substring(o.hierarchy, 1, org_cte.recursionlevel) = org_cte.hlevel          , o.hierarchy <> org_cte.hlevel ) select orgname, hlevel, recursionlevel  org_cte 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -