if exists ( select * from sys.procedures p where p.name = 'sp_V040ApplPlaceLoad' ) DROP PROCEDURE [dbo].[sp_V040ApplPlaceLoad]
GO
CREATE PROCEDURE [dbo].[sp_V040ApplPlaceLoad]
 @Xml xml
 ,@FileName varchar(50)
AS 
BEGIN

select
	T.c.value('./ID_MOP[1]','varchar(3)') as ID_MOP
	,case when T.c.value('./N_MOP[1]','varchar(254)')='' then NULL else T.c.value('./N_MOP[1]','varchar(254)') end as N_MOP
	,convert(datetime,T.c.value('./DATEBEG[1]','varchar(20)'),104) as DATEBEG
	,case when T.c.value('./DATEEND[1]','varchar(20)')='' then NULL else convert(datetime,T.c.value('./DATEEND[1]','varchar(20)'),104) end as DATEEND
into #V040
from @Xml.nodes('/packet/zap') T(c)

update t2
set t2.N_MOP=t1.N_MOP
	,t2.DATEEND=t1.DATEEND
from #V040 t1
join [IES].[T_V040_APPL_PLACE] t2 on (t1.ID_MOP = t2.ID_MOP and t1.DATEBEG = t2.DATEBEG)

insert into [IES].[T_V040_APPL_PLACE](V040ApplPlaceID, ID_MOP, N_MOP, DATEBEG, DATEEND)
select NEWID(), t1.ID_MOP, t1.N_MOP, t1.DATEBEG, t1.DATEEND
from #V040 t1
left join [IES].[T_V040_APPL_PLACE] t2 on (t1.ID_MOP = t2.ID_MOP and t1.DATEBEG = t2.DATEBEG)
where t2.V040ApplPlaceID is null

drop table #V040

END