尝试通过SQL构建树菜单:
DepID Name ParentID HaveParent
1 dep1 NULL 0
2 dep2 NULL 0
3 dep3 2 1
4 dep4 3 1
5 dep5 4 1
Declare @str nvarchar(MAX);
DECLARE @ID as integer = (select DepartmentID from tbl_Department where ParentID = 2);
IF (@ID > 0)
BEGIN
SET @str = '<ul class="navbar-mobile-sub__list list-unstyled js-sub-list">' +
STUFF((SELECT distinct '<li> <a href="OrganizationHierarchy.aspx?ID='
+ CONVERT(NVARCHAR(max), DepartmentID)
+'">'
+ CONVERT(NVARCHAR(max), DepartmentName)
+'</a>'
+ dbo.GetDep((select DepartmentID
from tbl_Department
where ParentID= @ID))
+'</li>'
from tbl_Department
where IsHaveParent = 1 AND ParentID = 2
FOR xml path('')), 1 , 1, '')
+ '</ul>'
END
ELSE
BEGIN
SET @str = '<ul class="navbar-mobile-sub__list list-unstyled js-sub-list">' + STUFF((SELECT distinct '<li> <a href="OrganizationHierarchy.aspx?ID='+ CONVERT(NVARCHAR(max), DepartmentID)+'">'+ CONVERT(NVARCHAR(max), DepartmentName) +'</a></li>' from tbl_Department where IsHaveParent = 1 AND ParentID = 2 FOR xml path('')), 1 , 1, '') + '</ul>'
END
print @ID;
print @str;
但是递归函数返回null
答案 0 :(得分:0)
正确的
ALTER FUNCTION dbo.getSubDep
(
@ID为整数
)
返回nvarchar(MAX)
AS
开始
Declare @str nvarchar(MAX) ;
DEclare @xxx integer ;
Declare @DepID integer ;
set @DepID = (select count(DepartmentID) from tbl_Department where ParentID = @ID )
IF (@DepID > 0)
BEGIN
set @xxx = (select DepartmentID from tbl_Department where tbl_Department.ParentID = @ID);
set @str = '<ul class="navbar-mobile-sub__list list-unstyled js-sub-list">' + STUFF((SELECT distinct ' <li> <a href="OrganizationHierarchy.aspx?ID='+ CONVERT(NVARCHAR(max), DepartmentName)+'">'+ CONVERT(NVARCHAR(max), DepartmentName) +'</a>' from tbl_Department where tbl_Department.DepartmentID =@ID FOR xml path('')), 1 , 1, '') + dbo.getSubDep(@xxx)+'</li>' + '</ul>'
END
ELSE
BEGIN
set @str = '<ul class="navbar-mobile-sub__list list-unstyled js-sub-list">' + STUFF((SELECT distinct ' <li> <a href="OrganizationHierarchy.aspx?ID='+ CONVERT(NVARCHAR(max), DepartmentName)+'">'+ CONVERT(NVARCHAR(max), DepartmentName) +'</a>' +'</li>' from tbl_Department where tbl_Department.DepartmentID =@ID FOR xml path('')), 1 , 1, '') + '</ul>'
END
RETURN @str
END
GO