前一篇文章中已經(jīng)可以取得所有部門的全稱,但現(xiàn)在又有個新的需求: 只想得到某一個部門的部門全稱,雖然可以用where條件來過濾,但是會有點(diǎn)小浪費(fèi)。 這時我們可以從后往前找,先看下效果:
最后一條就是,行得通! 但是怎么取出來呢? 用ParentUnitID排序? 但是實(shí)際生活中,部門可能調(diào)整或歸并,并不總是 UnitID > ParentUnitID. 所以需要一個類似于 標(biāo)識列的參照物:
1 Declare @utid int 2 Set @utid = 10 -- the target unit 3 ; 4 With CTE_Unit_Name_Special -- test: show the full name of every Unit 5 as( 6 select UnitID, 7 --UnitName, 8 Cast(UnitName as nvarchar(max)) as UnitName, 9 ParentUnitID,10 0 as IndexTemp -- identity11 from Unit12 where UnitID = @utid13 Union All -- Essential14 select U.UnitID, 15 (16 U.UnitName + '/' + CU.UnitName17 ) as UnitName, 18 U.ParentUnitID,19 (CU.IndexTemp + 1) as IndexTemp20 from Unit as U21 Inner Join CTE_Unit_Name_Special as CU22 on U.UnitID = CU.ParentUnitID23 where U.ParentUnitID != 0 24 )25 --select * from CTE_Unit_Name_Special26 select top 1 * from CTE_Unit_Name_Special27 --order by ParentUnitID asc -- only the situation where PUTID < UTID is suited28 order by IndexTemp desc -- need a reference substance, like a Identity column
結(jié)果不用再顯示了。。。 等等,剛想起來,部門表中有個列UnitLevel是標(biāo)識部門父子層次關(guān)系的,不管部門怎么調(diào)整,這個層次還是有順序的, 可以直接用, 一樣的。。。。
順便捎帶個以前寫的一個函數(shù):
1 -- Function - get a full unit name of one special unit 2 Create Function FN_GetFullUnitName(@unitID int) 3 Returns nvarchar(1000) 4 as 5 Begin 6 Declare @fullName nvarchar(1000), 7 @level smallint, 8 @parentUTID int 9 select @fullName = UnitName,10 @parentUTID = ParentUnitID,11 @level = UnitLevel12 from Unit13 where UnitID = @unitID14 15 if @level <= 216 return @fullName17 18 while @level > 219 Begin20 Set @unitID = @parentUTID21 select @fullName = UnitName + '/' + @fullName,22 @parentUTID = ParentUnitID,23 @level = UnitLevel24 from Unit25 where UnitID = @unitID26 End 27 return @fullName28 End29 go30 --Drop Function FN_GetFullUnitName31 --select dbo.FN_GetFullUnitName(10) -- 銷售部/售后科/客服部
新聞熱點(diǎn)
疑難解答
圖片精選