请有人看看这个 CTE 并告诉我它有什么问题?它只返回第一行(锚点)。
编辑: 这个应该可以工作,但我想知道表格和数据有什么问题!!!
Create table Menus (MenuID uniqueidentifier primary key, MenuName nvarchar(100))
Create table MenuItems (MenuItemID uniqueidentifier primary key, PID uniqueidentifier null, MenuID uniqueidentifier not null, MenuItemName nvarchar(100) not null)
insert into Menus values ('3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'Main')
insert into MenuItems values ('D3B92D1B-7AFA-4E11-AF01-9F6A00B1B2A9', '00000000-0000-0000-0000-000000000000', '3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'Books')
insert into MenuItems values ('70575C44-1EF8-497F-B7B8-A18300F645D7', '00000000-0000-0000-0000-000000000000', '3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'CDs')
insert into MenuItems values ('2D6ED5B3-4C6A-4907-8571-A196009727D7', '00000000-0000-0000-0000-000000000000', '3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'DVDs')
insert into MenuItems values ('3A1096E7-5FD2-4F77-9729-A19600973BDF', '2D6ED5B3-4C6A-4907-8571-A196009727D7', '3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'Movies')
insert into MenuItems values ('5C2AC1F8-DEE0-448B-B538-A19600F0839B', '00000000-0000-0000-0000-000000000000', '3AB564A7-1D2C-4C43-91E3-A191016CBE67', 'Cassetes')
GO
declare @MenuID uniqueidentifier
set @MenuID = '3AB564A7-1D2C-4C43-91E3-A191016CBE67'
;WITH
cte (MenuItemID, PID, Lvl)
AS
(
select MenuID as MenuItemID, cast(null as uniqueidentifier) as PID, 1
from Menus where MenuID = @MenuID
union all
select MenuItems.MenuItemID
, PID = case MenuItems.pid when '00000000-0000-0000-0000-000000000000' then @MenuID else MenuItems.pid end
, cte.Lvl + 1
from MenuItems
inner join cte on cte.MenuItemID = MenuItems.PID
where MenuItems.MenuID = @MenuID
)
select * from cte
编辑:结果应该是这样的:
3AB564A7-1D2C-4C43-91E3-A191016CBE67 NULL 1
D3B92D1B-7AFA-4E11-AF01-9F6A00B1B2A9 3AB564A7-1D2C-4C43-91E3-A191016CBE67 2
70575C44-1EF8-497F-B7B8-A18300F645D7 3AB564A7-1D2C-4C43-91E3-A191016CBE67 2
2D6ED5B3-4C6A-4907-8571-A196009727D7 3AB564A7-1D2C-4C43-91E3-A191016CBE67 2
5C2AC1F8-DEE0-448B-B538-A19600F0839B 3AB564A7-1D2C-4C43-91E3-A191016CBE67 2
3A1096E7-5FD2-4F77-9729-A19600973BDF 2D6ED5B3-4C6A-4907-8571-A196009727D7 3
提前致谢!
卡多