--do $$
--begin
--	if exists 
--	(
--		select * from pg_proc p
--		where p.proname = 'sp_rds_pregnanthospitalizationxml'
--	)
--	then
--		drop function public.sp_rds_pregnanthospitalizationxml(text, uuid, bit);
--	end if;
--end;
--$$ language plpgsql;
---- =============================================
---- Author:		Vitacore (с)
---- Create date: 2014-08-11
---- Description:	Выгрузка информации о госпитализации беременной
---- =============================================
--CREATE or Replace Function public.sp_RDS_PregnantHospitalizationXml
--(
--	"LpuCode" text = null
--,	"ID" UUID = null
--,	"IsNew" bit = '0'
--)
--RETURNS Void As 
--$$
--Declare	Result text;
--			QueueNameVar varchar(255);
--			ContentEncodingVar varchar(255);
--			TypeVar varchar(255);
--			OperationTypeVar text;
--			OwnerIDVar UUID;
--Begin	
--	if "IsNew" = '1'
--	then
--		OperationTypeVar := 'Insert';
--	elsif "IsNew" = '0' and exists (select * from akuz.T_MEDICALCARD_REGISTRATION m where m.MovementID = "ID")
--	then
--		OperationTypeVar := 'Update';
--	elsif "IsNew" = '0' and not exists (select * from akuz.T_MEDICALCARD_REGISTRATION m where m.MovementID = "ID")
--	then
--		OperationTypeVar := 'Delete';
--		Result := XMLELEMENT
--			  (
--				name "PREGNANT_HOSPITALIZATION"
--			  ,	XMLELEMENT
--				(
--					name header
--				,	XMLFOREST
--					(
--						"LpuCode" as "LPU"
--					,	OperationTypeVar as "TYPE"
--					,	"ID" as "ID"
--					)
--				)
--			  );
--	end if;

--	QueueNameVar := 'RDSMotherhood';
--	ContentEncodingVar := 'utf-8';
--	TypeVar := 'PREGNANT_HOSPITALIZATION';
--	OwnerIDVar := "ID";

--	if OperationTypeVar <> 'Delete'
--	then
--		select	
--		XMLELEMENT
--		(
--			name "PREGNANT_HOSPITALIZATION"
--		,	XMLELEMENT
--			(
--				name header
--			,	XMLFOREST
--				(
--					"LpuCode" as "LPU"
--				,	OperationTypeVar as "TYPE"
--				,	"ID" as "ID"
--				)
--			)
--		,	XMLELEMENT
--			(
--				name body
--			,	XMLFOREST
--				(
--					p.LastName as "LAST_NAME"
--				,	p.FirstName as "FIRST_NAME"
--				,	p.FatherName			as "FATHER_NAME"
--				,	to_char(p.Birthday, 'YYYY-MM-DD') as "BIRTHDAY"
--				,	to_char(m.MovementDate, 'YYYY-MM-DD') as "HOSPITALISATION_DATE"
--				,	to_char(m.MovementTime, 'YYYY-MM-DD HH:MI:SS') as "HOSPITALISATION_TIME"
--				)
--			)
--		)
--		from akuz.T_MEDICALCARD_REGISTRATION mcr
--		join akuz.T_MOVEMENT m  on m.MovementID = mcr.MovementID
--		join akuz.T_EVENT_BASE eb on eb.EventID = m.EmergencyEvent
--		join akuz.T_AMBULANCE_CARD ac on ac.AmbulanceCardID = eb.AmbulanceCard
--		join akuz.T_PATIENT p on p.PatientID = ac.Patient
--		into Result
--		where m.MovementID = "ID";
--	END if;

--	INSERT INTO akuz.T_RABBIT_SEND_OBJECT(RabbitSendObjectID, QueueName, Content, MessageID, Headers, ContentEncoding, Type, UserID, State, CreateDateTime, OwnerID)
--	select uuid_generate_v1(), QueueNameVar, Result, null, null, ContentEncodingVar, TypeVar, null, 0, Current_TimeStamp::TIMESTAMP, OwnerIDVar;
--End;
--$$ Language plpgsql;