2017-05-11 49 views
0

我有父子關係SQL表遞歸CTE SQL - 查找下一個可用的家長

LOCATIONDETAIL Table 
OID  NAME  PARENTOID 
1  HeadSite  0 
2  Subsite1  1 
3  subsite2  1 
4  subsubsite1 2 
5  subsubsite2 2 
6  subsubsite3 3 

RULESETCONFIG 
OID  LOCATIONDETAILOID VALUE 
1   1    30 
2   4    15 

如果我提供的輸入作爲LOCATIONDETAIL 6,我應該得到RULESETCONFIG值30 因爲 LOCATIONDETAIL 6,parentId的是3和用於LOCATIONDETAIL 3存在RULESETCONFIG沒有值, LOCATIONDETAIL 3具有其在RULESETCONFIG

值,如果我提供輸入作爲LOCATIONDETAIL 4父1,我應該得到RULESETCONFIG值15

我有代碼來填充樹,但不知道如何找到下一個可用的家長

;WITH GLOBALHIERARCHY AS 
     (
      SELECT A.OID,A.PARENTOID,A.NAME 
      FROM LOCATIONDETAIL A 
      WHERE OID = @LOCATIONDETAILOID 
      UNION ALL 
      SELECT A.OID,A.PARENTOID,A.NAME 
      FROM LOCATIONDETAIL A INNER JOIN GLOBALHIERARCHY GH ON A.PARENTOID = GH.OID 
     ) 
SELECT * FROM GLOBALHIERARCHY 

回答

0

這將返回值的下一個父項。如果您想查看全部內容,請從最終選擇中刪除頂部1。

dbFiddle

Declare @Fetch int = 4    

;with cteHB as (
     Select OID 
      ,PARENTOID 
      ,Lvl=1 
      ,NAME 
     From LOCATIONDETAIL 
     Where [email protected] 
     Union All 
     Select R.OID 
      ,R.PARENTOID 
      ,P.Lvl+1 
      ,R.NAME 
     From LOCATIONDETAIL R 
     Join cteHB P on P.PARENTOID = R.OID) 
Select Top 1 
     Lvl = Row_Number() over (Order By A.Lvl Desc) 
     ,A.OID 
     ,A.PARENTOID 
     ,A.NAME 
     ,B.Value 
From cteHB A 
Left Join RULESETCONFIG B on A.OID=B.OID 
Where B.VALUE is not null 
    and A.OID <> @Fetch 
Order By 1 Desc 

當返回@取= 4

Lvl OID PARENTOID NAME  Value 
2 2 1   Subsite1 15 

返回時@取= 6

Lvl OID PARENTOID NAME  Value 
1 1 0   HeadSite 30 
0

這應該做的工作:

;with LV as (
select OID ID,PARENTOID PID,NAME NAM, VALUE VAL FROM LOCATIONDETAIL 
left join RULESETCONFIG ON LOCATIONDETAILOID=OID 
), GH as (
select ID gID,PID gPID,NAM gNAM,VAL gVAL from LV where [email protected] 
union all 
select ID,PID,NAM,VAL FROM LV INNER JOIN GH ON gVAL is NULL AND gPID=ID 
) 
select * from GH WHERE gVAL>0 

看到這裏爲電子小演示:http://rextester.com/OXD40496