CREATE OR REPLACE FUNCTION dbo.fgetrelatedhierarchyrootentityid(IN par_rootentityid INTEGER, IN par_relatedname VARCHAR)
RETURNS INTEGER
AS
$BODY$
DECLARE
    var_EntityID INTEGER;
BEGIN
    SELECT
        e.entityid
        INTO var_EntityID
        FROM dbo.hierarchydefinition AS hd
        JOIN dbo.entity AS e
            ON hd.rootentityid = e.entityid
        WHERE hd.relatedrootentityid = par_RootEntityID AND LOWER(e.name) LIKE LOWER(par_RelatedName)
        LIMIT 1;
    RETURN var_EntityID;
END;
$BODY$
LANGUAGE  plpgsql;