Quantcast
Channel: Microsoft SQL Server
Viewing all articles
Browse latest Browse all 4871

SQL Server: CTE that lists organization hierarchy

$
0
0

I have a table Organizations. It has Id, Name, ParentId. simple.

I need to list the organizations, starting with parent, then each child, and and children of each child.

it sounds simple and I can list them, but so far, I'm not listing them in the order that I was hoping.

I want to be able to list by:

Parent

child

grandchild

child

child

next parent

child

child

etc

the following isn't quite what I want:

SQL
WITHCTEorgAS(SELECTx.CbpOrganizationId,x.CbpOrganizationName,x.ParentOrganizationIdFROMRFI.CbpOrganizationsxWITH(NOLOCK)WHEREx.ParentOrganizationIdisNULLUNIONALLSELECTy.CbpOrganizationId,y.CbpOrganizationName,y.ParentOrganizationIdFROMRFI.CbpOrganizationsyINNERJOINCTEorgONy.ParentOrganizationId=CTEorg.CbpOrganizationIdWHEREy.ParentOrganizationIdISNOTNULL)Select*FROMCTEorg

Viewing all articles
Browse latest Browse all 4871

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>