Code ALTERFUNCTION GetChildID(@IDVARCHAR(36)) RETURNS@ChildTABLE(ID VARCHAR(36),Name VARCHAR(50),ParentID VARCHAR(36)) AS BEGIN INSERTINTO@ChildSELECT ID,Name,ParentID FROM WorkCorps WHERE ParentID=@IDOR ID=@ID WHILE@@ROWCOUNT>0 BEGIN INSERTINTO@ChildSELECT A.ID,A.Name,A.ParentID FROM WorkCorps A INNERJOIN@Child B ON A.ParentID=B.ID WHERE A.ParentID NOTIN (SELECT ParentID FROM@Child) END
2 采用游标
Code ALTERFUNCTION GetID(@IDVARCHAR(36)) RETURNSVARCHAR(500) AS BEGIN DECLARE@RetValueVARCHAR(5000) DECLARE@TempIDVARCHAR(360) SET@TempID='' SET@RetValue='' --声明两个变量并附空值(赋空值很重要) DECLARE ID_cursor CURSORFORSELECT ID FROM WorkCorps WHERE ParentID=@IDORDERBY ID DESC --声明游标 定位到WHERE ParentID=@ID的ID OPEN ID_cursor FETCHNEXTFROM ID_cursor INTO@TempID WHILE(@@FETCH_STATUS=0) BEGIN IFLEN(@TempID)>0 SELECT@RetValue=@TempID+','+@RetValue IF((SELECTCOUNT(ID) FROM WorkCorps WHERE ParentID=@TempID)>0) BEGIN set@RetValue=@RetValue+','+ dbo.GetID(@TempID) END --判断子节点是否还有子节点有就递归 FETCHNEXTFROM ID_cursor INTO@TempID END CLOSE ID_cursor DEALLOCATE ID_cursor SELECT@RetValue=LEFT(@RetValue,LEN(@RetValue)-1)--处理末尾逗号 RETURN@ID+','+@RetValue--返回值