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

select
	T.c.value('./ID_SL[1]','varchar(5)') as ID_SL
	,case when T.c.value('./N_SL[1]','varchar(2000)')='' then NULL else T.c.value('./N_SL[1]','varchar(2000)') end as N_SL
	,case when T.c.value('./PG_SL[1]','varchar(10)')='' then NULL else T.c.value('./PG_SL[1]','varchar(10)') end as PG_SL
	,case when isnumeric(T.c.value('./K_SL[1]','varchar(20)'))=1 then cast(T.c.value('./K_SL[1]','varchar(20)') as decimal(3,2)) else null end AS K_SL
	,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 #V041
from @Xml.nodes('/packet/zap') T(c)

update t2
set t2.N_SL=t1.N_SL
	,t2.PG_SL=t1.PG_SL
	,t2.K_SL=t1.K_SL
	,t2.DATEEND=t1.DATEEND
from #V041 t1
join [IES].[T_V041_TREAT_COMPL_COEF] t2 on (t1.ID_SL = t2.ID_SL and t1.DATEBEG = t2.DATEBEG)

insert into [IES].[T_V041_TREAT_COMPL_COEF](V041TreatComplCoefID, ID_SL, N_SL, PG_SL, K_SL, DATEBEG, DATEEND)
select NEWID(), t1.ID_SL, t1.N_SL, t1.PG_SL, t1.K_SL, t1.DATEBEG, t1.DATEEND
from #V041 t1
left join [IES].[T_V041_TREAT_COMPL_COEF] t2 on (t1.ID_SL = t2.ID_SL and t1.DATEBEG = t2.DATEBEG)
where t2.V041TreatComplCoefID is null

drop table #V041

END