国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

SQL筆記

2024-07-21 02:51:07
字體:
來源:轉載
供稿:網友
SQL筆記 - CTE遞歸實例(續):顯示指定部門的全稱

前一篇文章中已經可以取得所有部門的全稱,但現在又有個新的需求: 只想得到某一個部門的部門全稱,雖然可以用where條件來過濾,但是會有點小浪費。 這時我們可以從后往前找,先看下效果:

最后一條就是,行得通! 但是怎么取出來呢? 用ParentUnitID排序? 但是實際生活中,部門可能調整或歸并,并不總是 UnitID > ParentUnitID. 所以需要一個類似于 標識列的參照物:

 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

結果不用再顯示了。。。 等等,剛想起來,部門表中有個列UnitLevel是標識部門父子層次關系的,不管部門怎么調整,這個層次還是有順序的, 可以直接用, 一樣的。。。。

順便捎帶個以前寫的一個函數:

 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)  -- 銷售部/售后科/客服部


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南溪县| 耒阳市| 佳木斯市| 兴安县| 邻水| 南昌市| 涟水县| 三亚市| 高唐县| 定西市| 禹城市| 凭祥市| 策勒县| 紫阳县| 社会| 葵青区| 遵化市| 桃园市| 岳普湖县| 藁城市| 玛曲县| 平邑县| 廉江市| 涟水县| 平凉市| 铜鼓县| 康保县| 嘉鱼县| 承德县| 即墨市| 苗栗县| 赤城县| 松原市| 灵璧县| 保定市| 睢宁县| 翁牛特旗| 余江县| 句容市| 兰州市| 蒙阴县|