---- =============================================
---- Author:		Dmitry
---- Create date: 05.07.2010
---- Description:	Возвращает DrugRequestList
---- =============================================
--CREATE OR REPLACE FUNCTION fn_GetDrugRequestList
--(
--	"Code" Integer -- код лекарственной формы (id T_DRUG_FORM)
--,	"OnDate" TimeStamp = NULL
--)
--RETURNS UUID AS
-- $$
--Declare _c int;
--	_Mnn int;
--	_Trn int;
--	_MedicationForms int;
--	_DoseView int;
--	_Dose varchar(255);
--	_DoseCount int;
--	_Doses decimal(31,10);
--	_VolumeView int;
--	_Weigth decimal(31,10);
--	_WeightView int;
--	_Volume decimal(31,10);
-- Begin
--	_c := case when "Code" < 0 Then ~("Code") Else "Code" End;

--	select Into
--		_Mnn, _Trn, _MedicationForms, _DoseView, _Dose, _DoseCount, _Doses, _VolumeView, _Weigth, _WeightView, _Volume
--		df.Mnn, df.Trn, df.MedicationForms, df.DoseView, df.Dose, df.DoseCount, df.Doses, df.VolumeView, df.Weigth, df.WeightView, df.Volume
--	from T_DRUG_FORM df
--	where df.Code = _c
--	limit 1;

--	return
--	(
--		select dr.BaseDrugRequestItemID
--		from akuz.T_BASE_DRUG_REQUEST_ITEM dr
--		inner join 
--			akuz.T_DRUG_REQUEST_LIST drl 
--			on dr.BaseDrugRequestItemID = dr.BaseDrugRequestItemID
--		where dr.BeginDate <= Coalesce("OnDate", Current_TimeStamp::TIMESTAMP) 
--		and drl.Mnn = _Mnn
--		And ((drl.Trn Is Null AND _Trn IS NULL) OR drl.Trn = _Trn)
--		and dr.MedicationForms = _MedicationForms
--		and drl.DoseView = _DoseView
--		and drl.Dose = _Dose
--		and drl.DoseCount = _DoseCount
--		and drl.Doses = _Doses
--		and ((drl.Volume IS NULL AND _Volume IS NULL) OR drl.Volume = _Volume)
--		and ((drl.VolumeView IS NULL AND _VolumeView IS NULL) OR drl.VolumeView = _VolumeView)
--		and ((drl.Weigth IS NULL AND _Weigth IS NULL) OR drl.Weigth = _Weigth)
--		and ((drl.WeightView IS NULL AND _WeightView IS NULL) OR drl.WeightView = _WeightView)
--		order by dr.BeginDate desc, drl.Trn Desc
--		Limit 1
--	);	
--END $$
--language plpgsql stable;