
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" int,"Gender" varchar,"FromAgeType" varchar,"ToAge" int,"ToAgeType" varchar,
	      "MinValue" numeric,"MaxValue" numeric,"MinCriticalValue" numeric,"MaxCriticalValue" numeric,	"UnitId" int,"UnitName" varchar	) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000
AS $BODY$
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= 'M' then a."Gender" ='M'
		when Gendervalue= 'F' then a."Gender" ='F'		  
		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= 'M' then a."Gender" ='M'
		when Gendervalue= 'F' then a."Gender" ='F'		  
		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
$BODY$;

------------------

create table "LabTemplateObservedValue"(
					"LabTemplateObservedValueId" bigserial primary key,
					"NewLabBookingDetailId" int references "NewLabBookingDetail"("NewLabBookingDetailId"),
					"LabMainDetailId" int references "LabMainDetail"("LabMainDetailId"),
					"LabTemplateHeaderId" int references "LabTemplateHeader"("LabTemplateHeaderId"),
					"MethodText" text,
					"InterpretationText" text,
					"Active" boolean default true
);

alter table "LabTemplateObservedValue" add column "CreatedBy" int references "Account"("AccountId"),
		add column "CreatedDate" timestamp without time zone;
------------------------