alter table  "LabTemplateDetail" add column "LabParameterHeaderId" int references "LabParameterHeader"("LabParameterHeaderId");

-----------------------
drop table "LabMainDetailCharge";
----------

CREATE OR REPLACE FUNCTION public."fetch_LabParameterDetails_on_conditions"(agetype text DEFAULT NULL::text, headerid integer DEFAULT NULL::integer, fromage integer DEFAULT NULL::integer, gendervalue text DEFAULT NULL::text)
 RETURNS TABLE("LabParameterDetailId" bigint, "LabParameterHeaderId" integer, "Gender" character varying, "FromAgeType" character varying, "ToAge" integer, "ToAgeType" character varying, "MinValue" numeric, "MaxValue" numeric, "MinCriticalValue" numeric, "MaxCriticalValue" numeric, "UnitId" integer, "UnitName" character varying)
 LANGUAGE plpgsql
AS $function$
declare labdata INTEGER := 0;
BEGIN
select count(*) into labdata
from "LabParameterDetail" a 
	where a."LabParameterHeaderId" = HeaderId  and a."FromAgeType" = AgeType	
and case when Gendervalue= '' then 1=1
		when Gendervalue is null then 1=1
		when Gendervalue= 'Male' then a."Gender" ='Male'
		when Gendervalue= 'Female' then a."Gender" ='Female'		  
		else coalesce(a."Gender",'All') = 'All' END
and (FromAge >= a."FromAge" and FromAge <= a."ToAge");

return query
with cts as (
 select a."LabParameterDetailId" ,a."LabParameterHeaderId",a."Gender" ,a."FromAgeType" ,a."ToAge" ,	a."ToAgeType" ,	a."MinValue" ,	a."MaxValue" ,
 a."MinCriticalValue" ,	a."MaxCriticalValue" ,	a."UnitId",	lv."Name" as "UnitName"
 	from "LabParameterDetail" a 
 	join "LookupValue" lv on lv."LookupValueId" = a."UnitId" 
	where a."LabParameterHeaderId" = HeaderId  and a."FromAgeType" = AgeType	
		and case when Gendervalue= '' then 1=1
		when Gendervalue is null then 1=1
		when Gendervalue= 'Male' then a."Gender" ='Male'
		when Gendervalue= 'Female' then a."Gender" ='Female'		  
		else coalesce(a."Gender",'All') = 'All' END
and (FromAge >= a."FromAge" and FromAge <= a."ToAge") )
select * from cts
 union
select a."LabParameterDetailId" ,a."LabParameterHeaderId",a."Gender" ,a."FromAgeType" ,a."ToAge" ,	a."ToAgeType" ,	a."MinValue" ,	a."MaxValue" ,
 a."MinCriticalValue" ,	a."MaxCriticalValue" ,	a."UnitId",	lv."Name" as "UnitName"
	from "LabParameterDetail" a 
	join "LookupValue" lv on lv."LookupValueId" = a."UnitId" 
	where a."LabParameterHeaderId" = HeaderId  and a."FromAgeType" = AgeType
and (FromAge >= a."FromAge" and FromAge <= a."ToAge") and labdata = 0;
END
$function$
;



---------