--CREATE or Replace Function RecalculateMKBTreeParams
--(
--	"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_MKB m into _ChCount WHERE m.ParentID IS NULL;
--	ELSE 
--		SELECT COUNT(*) FROM akuz.T_MKB 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.MkbID FROM akuz.T_MKB m WHERE m.ParentID IS NULL ORDER BY m.MkbID LOOP
--				select (select * from RecalculateMKBTreeParams(_Id, "Begin", _NestedLevel)) into "End";
--				UPDATE akuz.T_MKB 
--				SET 	LeftIndex = "Begin"
--				,	RightIndex = "End"
--				,	TreeLevel = "Level"
--				WHERE MkbID = _ID;
--				"Begin" := "End" + 1;
--			END LOOP;					
--		ELSE
--			"Begin" := "Begin" + 1;
--			FOR _Id IN select m.MkbID FROM akuz.T_MKB m WHERE m.ParentID = "ParentID" ORDER BY m.MkbID LOOP
--				select (select * from RecalculateMKBTreeParams(_Id, "Begin", _NestedLevel)) into "End";
--				UPDATE akuz.T_MKB 
--				SET 	LeftIndex = "Begin"
--				,	RightIndex = "End"
--				,	TreeLevel = "Level"
--				WHERE MkbID = _ID;
--				"Begin" := "End" + 1;
--			END LOOP;
--		END if;		
--		"End" := "End" + 1;
--	END if;
--End;
--$$ Language plpgsql;