我有父子关系SQL表
y
如果我提供输入为LOCATIONDETAIL 6,我应该将RULESETCONFIG值设为30 因为 LOCATIONDETAIL 6,parentid为3,对于LOCATIONDETAIL 3,RULESETCONFIG没有任何价值, LOCATIONDETAIL 3有父1,其值在RULESETCONFIG
中如果我提供输入为LOCATIONDETAIL 4,我应该得到RULESETCONFIG值15
我有填充树的代码,但不知道如何找到下一个可用的父
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
答案 0 :(得分: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 ID=@OID
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
答案 1 :(得分:0)
这将返回具有值的下一个父级。如果要查看全部,请从最终选择中删除前1个。
<强> dbFiddle 强>
示例强>
Declare @Fetch int = 4
;with cteHB as (
Select OID
,PARENTOID
,Lvl=1
,NAME
From LOCATIONDETAIL
Where OID=@Fetch
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
@ Fetch = 4
时返回Lvl OID PARENTOID NAME Value
2 2 1 Subsite1 15
@ Fetch = 6
时返回Lvl OID PARENTOID NAME Value
1 1 0 HeadSite 30