if exists ( select * from sys.procedures p where p.name = 'sp_V025KPC' ) DROP PROCEDURE [dbo].[sp_V025KPC]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_V025KPC]
 @Xml xml
 ,@FileName varchar(50)
AS 
BEGIN

	select 
		 T.c.value('./IDPC[1]', 'varchar(4)') AS IDPC
		,T.c.value('./N_PC[1]', 'varchar(255)') AS N_PC
		,case when T.c.value('./DATEBEG[1]', 'varchar(20)')='' then null else CONVERT(datetime,T.c.value('./DATEBEG[1]', 'varchar(20)'),104) end 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 #V025
	from @xml.nodes('/packet/zap') T(c)
	
	update t2 
	set  t2.N_PC=t1.N_PC
		,t2.DATEEND=t1.DATEEND
	from #V025 t1
	join [IES].[T_V025_KPC] t2 on (t1.IDPC=t2.IDPC and t1.DATEBEG = t2.DATEBEG)

	insert into [IES].[T_V025_KPC]([V025KpcID],IDPC,N_PC,DATEBEG,DATEEND)
	select newid(),t1.IDPC,t1.N_PC,t1.DATEBEG,t1.DATEEND
	from #V025 t1
	left join [IES].[T_V025_KPC] t2 on (t1.IDPC=t2.IDPC and t1.DATEBEG = t2.DATEBEG)
	where t2.IDPC is null
		
	drop table #V025
END