0

参考这篇文章,这里是整体问题和代码:

declare @tbl table (MenuItemID uniqueidentifier, PID uniqueidentifier, MenuID uniqueidentifier, SO tinyint, lvl tinyint)
;WITH 
cte (MenuItemID, PID, MenuID, SO, lvl) AS 
(
    select MenuItemID, PID, MenuID, SO, 0 from MenuItems
        where del = 0 and Perms = 1 and MenuID = @MenuID and MenuID = PID
    UNION ALL
    SELECT MenuItems.MenuItemID, MenuItems.PID, MenuItems.MenuID, MenuItems.SO, cte.lvl + 1 FROM MenuItems 
        JOIN cte ON cte.MenuItemID = MenuItems.PID
    ) 
    select * from cte
        ORDER BY lvl, SO
insert into @tbl select * from cte

declare @tbl2 table (MenuItemID uniqueidentifier, PID uniqueidentifier, MenuID uniqueidentifier, SO tinyint, lvl tinyint)
;with hier (MenuItemID, PID, MenuID, SO, lvl, FullSO) as
(select l0.*, convert(varchar(max),right('000'+convert(varchar(3),SO),3)) FullSO 
 from @tbl l0 where lvl=0
 union all
 select ln.*, lp.FullSO+','+right('000'+convert(varchar(3),ln.SO),3) FullSO
 from @tbl ln
 join hier lp on ln.PID = lp.MenuItemID)

insert into @tbl2 
 select MenuItemID, 
       PID, 
       MenuID,
       rank() over (partition by PID order by SO) SO,
       lvl
from hier
order by FullSO, SO

 update MenuItems set SO = h.SO
    from MenuItems as mi
    join @tbl2 h on mi.MenuItemID = h.MenuItemID and mi.MenuID = h.MenuID

我想知道这段代码是否有更简单和更短的方法?

提前致谢,

卡多

4

1 回答 1

1

您仍然需要递归 CTE 来确定层次结构的哪些顶级记录具有 del = 0 和 Perms = 1,但以下应该更简单:

WITH cte AS 
(select MenuItemID, PID, MenuID, SO, 
        rank() over (partition by PID order by SO) newSO
 from MenuItems
 where del = 0 and Perms = 1 and MenuID = @MenuID and MenuID = PID
 UNION ALL
 SELECT m.MenuItemID, m.PID, m.MenuID, m.SO, 
        rank() over (partition by m.PID order by m.SO) newSO
 FROM MenuItems m
 JOIN cte c ON c.MenuItemID = m.PID
) 
update MenuItems set SO = h.newSO
from MenuItems as mi
join cte h on mi.MenuItemID = h.MenuItemID and mi.MenuID = h.MenuID;

SQLFiddle在这里

于 2013-04-14T18:51:04.357 回答