'--- Create the function ("CREATE"), define what it will return ("RETURNS") and what it will do to get the
'--- result ("AS", "BEGIN"/"END")
CREATE FUNCTION AFM_getChildren(@IncludeParent bit, @DataID int)
RETURNS @retFindChildren TABLE (DataID int, ParentID int)
AS
BEGIN
'--- If the IncludeParent parameter is set to 1 the first entry of the table is filled with the
'--- information about the object that is queried. In most cases rather useless, unless you need to
'--- know the parent object for all objects, including the start object, in your query.
IF (@IncludeParent=1)
BEGIN
INSERT INTO @retFindChildren SELECT DataID, ParentID FROM dtree WHERE DataID=@DataID
END
'--- Declare temporary variables and temporary table and open the table for writing.
DECLARE @ChildID int, @ChildsParentID int
DECLARE RetrieveChildren CURSOR STATIC LOCAL FOR SELECT DataID, ParentID FROM dtree WHERE ParentID=@DataID
OPEN RetrieveChildren
'--- Loop through the DTREE table for every object found as a child of the previously found objects,
'--- insert them all in the temporary table with the newly found result. Continue the loop until
'--- nothing more is found.
FETCH NEXT FROM RetrieveChildren INTO @ChildID, @ChildsParentID
WHILE (@@FETCH_STATUS = 0)
BEGIN
INSERT INTO @retFindChildren SELECT * FROM AFM_GetChildren(0,@ChildID)
INSERT INTO @retFindChildren VALUES(@ChildID, @ChildsParentID)
FETCH NEXT FROM RetrieveChildren INTO @ChildID, @ChildsParentID
END
'--- Close and release the temporary table
CLOSE RetrieveChildren
DEALLOCATE RetrieveChildren
RETURN
END