if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_BranchLoad_folder]') and xtype = N'P')
drop procedure [dbo].[sp_BranchLoad_folder]
GO
create procedure dbo.sp_BranchLoad_folder @x xml
 ,@FileID uniqueidentifier = null
 ,@Worker uniqueidentifier = null
as
begin

SELECT 
  newid() as [ID]
 ,T.c.value('../HEADER[1]/FILENAME[1]', 'varchar(26)') AS [FILENAME]
 ,T.c.value('../HEADER[1]/MO[1]', 'varchar(6)') AS [MO]
 ,T.c.value('./N_ZAP[1]', 'int') AS [N_ZAP]
 ,T.c.value('./TYPE[1]', 'varchar(6)') AS [TYPE]
 ,T.c.value('./BR_CODE[1]', 'varchar(17)') AS BR_CODE
 ,T.c.value('./NAME[1]', 'varchar(266)') AS NAME
 ,T.c.value('./ADDRESS[1]', 'varchar(255)') AS [ADDRESS]
 ,T.c.value('./PHONE[1]', 'varchar(255)') AS PHONE
 ,T.c.value('./RUCV[1]', 'varchar(255)') AS RUCV
 ,T.c.value('./ACTIVE[1]', 'int') AS ACTIVE
 ,T.c.value('./BranchID[1]', 'uniqueidentifier') AS BranchID--
INTO #ZAP
FROM @x.nodes('BRANCH//BODY') T(c)

create table #Errors
(
	CODE int,
	COMMENT varchar(250)
)

insert into #Errors (CODE,COMMENT)
select 4, 'Неверный тип операции. N_ZAP('+cast(N_ZAP as varchar)+')'
from #ZAP
where [TYPE]<>'Insert' and [TYPE]<>'Update' and [TYPE]<>'Delete'

update zap
set BranchID = br.BranchID
from #ZAP zap
join ISZL.T_F003 lm on lm.MCOD = zap.MO
join ISZL.T_BRANCH br on br.BR_CODE = zap.BR_CODE


insert into #Errors (CODE,COMMENT)
select 1, 'Обязательное поле BR_CODE. N_ZAP('+cast(N_ZAP as varchar)+')'
from #ZAP
where BR_CODE = '' or BR_CODE is null

---- DEBUG
--select * from #ZAP zap
--select* from #Errors

--DROP TABLE #ZAP
--DROP TABLE #Errors
---- end DEBUG

--Insert
	-- нельзя удалять, тк могут быть отделения в подразделении
	-- удаляем, если есть
	--delete br from [ISZL].[T_BRANCH] br
	--join #ZAP zap on br.BranchID = zap.BranchID
	insert into #Errors (CODE,COMMENT)
	select 2, 'Подразделение было добавлено ранее. N_ZAP('+cast(N_ZAP as varchar)+')' 
	from #ZAP
	where BranchID is not null and [TYPE]='Insert'

	-- вставка, если нет ошибок
	INSERT INTO [ISZL].[T_BRANCH]
	([BranchID],[BR_CODE],[NAME],[PHONE],[ADDRESS],[RUCV],[ACTIVE],[F003Mo])
	select [ID]
		,zap.BR_CODE
		,zap.NAME
		,zap.PHONE
		,zap.[ADDRESS]
		,zap.RUCV
		,(case when zap.ACTIVE = 0 then 0 else 1 end)
		,zap.MO
	from #ZAP zap
	where ((select COUNT(*) from #Errors) = 0) and [TYPE]='Insert'



--Update
	UPDATE t
	   SET [NAME] = zap.Name
		  ,[PHONE] = zap.PHONE
		  ,[ADDRESS] = zap.[ADDRESS]
		  ,[RUCV] = zap.RUCV
		  ,[ACTIVE] = (case when zap.ACTIVE = 0 then 0 else 1 end)
		  ,[F003Mo] = zap.MO
	from [ISZL].[T_BRANCH] t
	join #ZAP zap on t.BranchID = zap.BranchID
	WHERE ((select COUNT(*) from #Errors) = 0) and t.BranchID = zap.BranchID and [TYPE] = 'Update'

	IF COL_LENGTH('ISZL.T_BRANCH', 'FILENAME') IS not NULL
	BEGIN
		update t1
		set t1.[FILENAME] = z.[FILENAME]
		from ISZL.T_BRANCH t1
		join #ZAP z on z.BranchID = t1.[BranchID]
		where((select COUNT(*) from #Errors) = 0) and [TYPE] = 'Update'
	END
	
	-- вставка, если не найдена
	INSERT INTO [ISZL].[T_BRANCH]([BranchID],[BR_CODE],[NAME],[PHONE],[ADDRESS],[RUCV],[ACTIVE],[F003Mo])
	select [ID]
		,zap.BR_CODE
		,zap.NAME
		,zap.PHONE
		,zap.[ADDRESS]
		,zap.RUCV
		,(case when zap.ACTIVE = 0 then 0 else 1 end)
		,zap.MO
	from #ZAP zap
	where ((select COUNT(*) from #Errors) = 0) and zap.BranchID is null and [TYPE] = 'Update'


-- Delete

	insert into #Errors
	select 3, 'Запись не найдена в ранее загруженных списках. N_ZAP('+cast(N_ZAP as varchar)+')' 
	from #ZAP zap
	where zap.BranchID is null and [TYPE] = 'Delete'

	delete t
	from [ISZL].[T_BRANCH] t, #ZAP zap
	WHERE (select COUNT(*) from #Errors) = 0 and t.BranchID = zap.BranchID and [TYPE] = 'Delete'

	IF COL_LENGTH('ISZL.T_BRANCH', 'FILENAME') IS not NULL
	BEGIN
		update t1
		set t1.[FILENAME] = z.[FILENAME]
		from ISZL.T_BRANCH t1
		join #ZAP z on z.[ID] = t1.[BranchID]
		where ((select COUNT(*) from #Errors) = 0) and ([TYPE] = 'Insert' or  (z.BranchID is null and [TYPE] = 'Update'))
	END


select (case 
	   when (select COUNT(*) from #Errors) = 0 
	   then cast(1 as bit)
	   else case
			when (select COUNT(*) from #Errors) > 0
			then cast(0 as bit)
			end
	   end),
	   '<?xml version="1.0" encoding="Windows-1251"?>' 
		+ 
		(
			SELECT 
				CODE as 'CODE'
				,COMMENT as 'COMMENT'
			FROM #Errors 
			FOR XML PATH('ERR'),ROOT('ROOT')
		)

DROP TABLE #ZAP
DROP TABLE #Errors
end
