--CREATE or Replace Function RecalculateMKBOTreeParams
--(
--	"ParentID" UUID = NULL,
--	"Begin" INT = 1,
--	"End" OUT INT ,
--	"Level" INT = 0
--)
--As 
--$$
--Declare
--	_ChCount int;
--	_ID UUID; 
--	_NestedLevel INT;
--Begin
--	IF "ParentID" IS NULL 
--	then
--		SELECT COUNT(*) FROM akuz.T_MKBO m into _ChCount WHERE m.ParentID IS NULL;
--	ELSE 
--		SELECT COUNT(*) FROM akuz.T_MKBO m into _ChCount WHERE m.ParentID = "ParentID";
--	end if;
	
--	IF _ChCount = 0 or _ChCount is NULL
--	then
--		"End" := "Begin" + 1;
--	ELSE
--		_NestedLevel := "Level" + 1;		
--		IF "ParentID" IS NULL
--		then
--			"Begin" := 1;
--			FOR _Id IN select m.MkboID FROM akuz.T_MKBO m WHERE m.ParentID IS NULL ORDER BY m.MkboID LOOP
--				select (select * from RecalculateMKBOTreeParams(_Id, "Begin", _NestedLevel)) into "End";
--				UPDATE akuz.T_MKBO 
--				SET 	LeftIndex = "Begin"
--				,	RightIndex = "End"
--				,	TreeLevel = "Level"
--				WHERE MkboID = _ID;
--				"Begin" := "End" + 1;
--			END LOOP;				
--		ELSE
--			"Begin" := "Begin" + 1;
--			FOR _Id IN select m.MkboID FROM akuz.T_MKBO m WHERE m.ParentID = "ParentID" ORDER BY m.MkboID LOOP
--				select (select * from public.RecalculateMKBOTreeParams(_Id, "Begin", _NestedLevel)) into "End";
--				UPDATE akuz.T_MKBO 
--				SET 	LeftIndex = "Begin"
--				,	RightIndex = "End"
--				,	TreeLevel = "Level"
--				WHERE MkboID = _ID;
--				"Begin" := "End" + 1;
--			END LOOP;
--		END if;		
--		"End" := "End" + 1;
--	END if;
--End;
--$$ Language plpgsql;