-- =============================================
-- Author:		Marat Zigangaraev
-- Create date: 19.11.2014
-- Description:	Проверка совпадения номера дома или вхождения в диапазон.
--				Вызов из dbo.fn_CheckAddress()
-- =============================================
DROP FUNCTION IF EXISTS fn_CheckHouse;
CREATE FUNCTION fn_CheckHouse(h varchar(128), hs varchar(128))
	RETURNS Boolean AS
 $$
	DECLARE	
	_idx Integer;
	_prev Integer; 
	_from varchar(128);
	_to varchar(128);
 Begin
	_idx := strpos(hs, '-');
	_prev := 0;

	if _idx > 0
	then _from := substring(hs from _prev for (_idx - _prev));
		_prev := _idx + 1;		
		_to := substring(hs from (_idx + 1) for (char_length(hs) + 1 - _prev));
		if isnumeric(h) = 't'
		then	
			if _from::int <= h::int and h::int <= _to::int 
			then return '1'; 
			else return '0'; 
			end if;
		else	
			if _from <= h and h <= _to
			then return '1';
			else return '0';
			end if;
		end if;
	end if;
	
	_to = substring(hs from _prev for (char_length(hs) + 1 - _prev));
	if _to = h then return '1'; else return '0'; end if;
END $$
language plpgsql immutable;