DROP FUNCTION IF EXISTS fn_GetParentV004;
CREATE FUNCTION fn_GetParentV004("Id" int)
RETURNS int AS
 $$
 declare	_code varchar(20);
		_len int;
 Begin
	select t.Id
	from akuz.T_V004_SPECIALITY t
	into _code
	where t.Id = "Id";
	_len := Char_Length(_code);

	if _len > 4
	then
		_code := SUBSTRING(_code from 1 for 4);
		_len := 4;
		if exists (select * from akuz.T_V004_SPECIALITY t where t.Id = cast(_code as int))
		then	return _code;
		end if;
	end if;

	if _len = 4
	then
		_code := SUBSTRING(_code from 1 for 2);
		_len := 2;
		if exists (select * from akuz.T_V004_SPECIALITY t where t.Id = _code::int)
		then	return _code;
		end if;
	end if;

	if _len = 2
	then	return SUBSTRING(_code from 1 for 1);
	end if;

	return null;
	
END $$
language plpgsql stable;