IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_SetFreeBedsXml]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_SetFreeBedsXml]
--GO
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
---- =============================================
---- Author:		Vitacore (с)
---- Create date: 2015-05-24
---- Description:Загрузка информации о количестве свободных коек в отделений в RDS 
---- =============================================
--CREATE PROCEDURE [dbo].[sp_SetFreeBedsXml]
--	@LpuCode varchar(max) = null,
--	@Xml xml = null,
--	@IsNew bit = 1,
--	@ID uniqueidentifier = null
--AS
--BEGIN

--	declare @OperationType varchar(max) = null

--SET NOCOUNT ON;
--	IF (@Xml is not null)
--		BEGIN
--		-- Generate table #FREE_BEDS
--		select				
--				T.c.value('./header[1]/TYPE[1]', 'varchar(max)') as [OperationType]
--				,T.c.value('./header[1]/LPU[1]', 'varchar(6)') as [LpuMain]
--				,T.c.value('./header[1]/ID[1]', 'uniqueidentifier') as [ID]
--				,T.c.value('./body[1]/DLSB[1]', 'uniqueidentifier') as [Dlsb]
--				,T.c.value('./body[1]/AMOUNT[1]', 'int') as [Amount]
--				,T.c.value('./body[1]/ACTUAL_DATE[1]', 'datetime') as [ActualDate] 
--			INTO #FREE_BEDS
--		from @Xml.nodes('FREE_BEDS_INFORMATION') T(c)
--		select @OperationType = (select OperationType from #FREE_BEDS)

--		if(@OperationType <> 'Delete')
--		BEGIN
--		-- update [RDS].T_FREE_BEDS_INFORMATION
--		update fbi
--		set
--			fbi.[Amount] = fb.[Amount]
--			,fbi.[ActualDate] = fb.[ActualDate]
--		from [RDS].T_FREE_BEDS_INFORMATION fbi
--		join #FREE_BEDS fb on fb.ID = fbi.ID 
 
--		-- INSERT [RDS].T_FREE_BEDS_INFORMATION
--		INSERT INTO [RDS].T_FREE_BEDS_INFORMATION
--		(FreeBedsInformationID, ActualDate, Amount, ID, DivisionLinkStructureBed)
--		SELECT
--			newID()
--			,fb.[ActualDate]
--			,fb.[Amount]
--			,fb.ID
--			,(select TOP 1 dlsb.[DivisionLinkStructureBedID] from [RDS].T_DIVISION_LINK_STRUCTURE_BED dlsb where dlsb.ID = fb.Dlsb or dlsb.DivisionLinkStructureBedID = fb.Dlsb)
--		from #FREE_BEDS fb
--		where not exists (
--			select * 
--			from [RDS].T_FREE_BEDS_INFORMATION fbi1
--			join #FREE_BEDS fb1 on fb1.ID = fbi1.ID 
--		)
		
--		END
--		ELSE
--		BEGIN
--			delete fbi
--			from [RDS].T_FREE_BEDS_INFORMATION fbi
--			join #FREE_BEDS fb on fb.[ID] = fbi.ID
--		END
--		-- Drop table
--		DROP TABLE #FREE_BEDS
--		END
--END
--GO