---- =============================================
---- Author:		Vitacore (с)
---- Create date: 2015-05-24
---- Description:Загрузка информации о количестве свободных коек в отделений в RDS 
---- =============================================
DROP FUNCTION if exists sp_SetFreeBedsXml(text, xml, boolean, uuid);
--CREATE OR REPLACE FUNCTION sp_SetFreeBedsXml
--(
--	"LpuCode" text DEFAULT NULL::text
--,	"Xml" xml DEFAULT NULL::xml
--,	"IsNew" integer = 1::boolean
--,	"ID" uuid DEFAULT NULL::uuid
--)
--RETURNS void AS
--$BODY$
--Declare	_OperationType text;
--begin
--	if "Xml" is not null
--	then
--		-- Generate table #FREE_BEDS
--		Drop Table If Exists TmpFREE_BEDS;
--		Create Temp Table TmpFREE_BEDS
--		As
--		select  (xpath('/FREE_BEDS_INFORMATION/header[1]/TYPE[1]/text()', x))[1]::text					as OperationType
--		,	(xpath('/FREE_BEDS_INFORMATION/header[1]/LPU[1]/text()', x))[1]::text					as LpuMain
--		,	(xpath('/FREE_BEDS_INFORMATION/header[1]/ID[1]/text()', x))[1]::text::uuid				as ID
--		,	(xpath('/FREE_BEDS_INFORMATION/body[1]/DLSB[1]/text()', x))[1]::text::uuid				as Dlsb
--		,	(xpath('/FREE_BEDS_INFORMATION/body[1]/AMOUNT[1]/text()', x))[1]::text::int				as Amount
--		,	to_timestamp((xpath('/FREE_BEDS_INFORMATION/body[1]/ACTUAL_DATE[1]/text()', x))[1]::text, 'DD.MM.YYYY')	as ActualDate	
--		from
--		(
--			select "Xml" as x
--		) t;

--		_OperationType := (select OperationType from TmpFREE_BEDS limit 1);
		
--		if _OperationType <> 'Delete'
--		then
--			-- update [RDS].T_FREE_BEDS_INFORMATION
--			update RDS.T_FREE_BEDS_INFORMATION fbi
--			set	Amount = fb.Amount
--			,	ActualDate = fb.ActualDate
--			from TmpFREE_BEDS fb 
--			where fb.ID = fbi.ID;
 
--			-- INSERT [RDS].T_FREE_BEDS_INFORMATION
--			insert into RDS.T_FREE_BEDS_INFORMATION(FreeBedsInformationID, ActualDate, Amount, ID, DivisionLinkStructureBed)
--			select gen_random_uuid(), fb.ActualDate, fb.Amount, fb.ID
--			,(select dlsb.DivisionLinkStructureBedID from RDS.T_DIVISION_LINK_STRUCTURE_BED dlsb where dlsb.ID = fb.Dlsb or dlsb.DivisionLinkStructureBedID = fb.Dlsb limit 1)
--			from TmpFREE_BEDS fb
--			where not exists 
--			(
--				select * 
--				from RDS.T_FREE_BEDS_INFORMATION fbi1
--				inner join 
--					TmpFREE_BEDS fb1 
--					on fb1.ID = fbi1.ID 
--			);
--		else
--			delete from RDS.T_FREE_BEDS_INFORMATION fbi
--			where exists
--			(
--				select* from TmpFREE_BEDS fb where fb.ID = fbi.ID
--			);
--		end if;
		
--		-- Drop table
--		drop TABLE if exists TmpFREE_BEDS;
--	end if;
--end;
--$BODY$
--  LANGUAGE plpgsql VOLATILE
--  COST 100;
--ALTER FUNCTION sp_SetFreeBedsXml(text, xml, boolean, uuid)
--  OWNER TO postgres;