DROP FUNCTION IF EXISTS dbo.fn_GetState;

CREATE FUNCTION dbo.fn_GetState
(
	"AmbulanceCardID" uuid
,	"Profile" integer
)
RETURNS uuid AS
$BODY$	
declare	_lpuMain UUID;
	_patient UUID;
	_regId UUID;
Begin		
	select into
		_patient, _lpuMain
		ac.Patient, ac.CardLpu 
	from akuz.T_AMBULANCE_CARD ac
	where ac.AmbulanceCardID = "AmbulanceCardID";
	_regId := fn_GetRegistration(_patient, null, "Profile");

	return
	(
		select r.State 
		from akuz.T_REGISTRATION r
		where r.LpuMain = _lpuMain 
		and r.Status = 1 
		and r.RegistrationID = _regId
		limit 1
	);
END $BODY$
  LANGUAGE plpgsql;
--ALTER FUNCTION fn_getstate(uuid, integer) OWNER TO postgres;
