--CREATE OR REPLACE FUNCTION fn_GetRecipeDrugFormLim("RecipeID" uuid)
--RETURNS integer AS
--$BODY$
--Begin
--	return
--	(
--		Select case when l.DateEnd is null or l.DateEnd >= r.RecipeDate then l.Code end
--		From akuz.T_RECIPE r
--		left Join 
--			akuz.T_DRUG_FORM_LIM l 
--			On l.DrugForm = r.DrugFormCode
--		left Join 
--			akuz.T_BENEFITS b 
--			On b.BenefitsID = r.Benefits
--		left Join 
--			vclib.T_ENUMS e 
--			On e.EnumID = b.BenefitViews
--		Where r.MedicalRecordID = "RecipeID" 
--		And l.DateBegin <= r.RecipeDate 
--		And
--		(
--			(e.Code = 1 And l.FED = '1') 
--			Or 
--			(e.Code = 6 And l.PSN = '1') 
--			Or
--			((e.Code = 2 Or e.Code = 3) And l.REG = '1')
--		)
--		Order by l.DateBegin desc
--		Limit 1
--	);	
--END $BODY$
--  LANGUAGE plpgsql volatile
--  COST 100;
--ALTER FUNCTION fn_getrecipedrugformlim(uuid)
--  OWNER TO postgres;
