IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_UpdateDispDirectList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_UpdateDispDirectList]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[RDS].[sp_UpdateDispDirectList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [RDS].[sp_UpdateDispDirectList]
GO
-- =============================================
-- Description: Обновить список по диспансеризации за текущий year(getdate()) год
-- =============================================
CREATE PROCEDURE [RDS].[sp_UpdateDispDirectList] 
(
    @cnt INTEGER OUTPUT
)
as
begin
	set @cnt = (select count(*) from [RDS].T_DISP_DIRECT)
	--select @cnt
	 INSERT INTO [RDS].T_DISP_DIRECT
	 (
		[DispDirectID],
		[ID_PAC],
		[FAM],
		[IM],
		[OT],
		[DR],
		[SPOLIS],
		[NPOLIS],
		[DOCSER],
		[DOCNUM],
		--[COMENTP],
		[TEL],
		--[MR],
		[YEAR],
		--[DispDirectFile],
		[W],
		[DOCTYPE],
		--[DispDirect],
		[SNILS_P],
		[SNILS_D],
		[VPOLIS],
		[Quarter],
		[CODE_SMO],
		[CODE_MO],
		[ENP]
	 )
	 select 
	 newid()
	 , p.PatientID
	 , p.LastName
	 , p.FirstName
	 , p.FatherName
	 , p.Birthday
	 , p.PolisSerial
	 , p.PolisNumber	 
	 , p.DocSeries
	 , p.DocNumber
	 , p.Phone
	 , year(getdate())--[YEAR]
	 , p.Sex
	 , p.DocType
	 , p.SNILS
	 , p.SNILS_D
	 , p.PolicyForm
	 , DATEPART(QUARTER, p.Birthday)--[Quarter]
	 , p.F002Smo
	 , p.LpuMain
	 , p.[ENP]
	 from [RDS].T_PATIENT p
	 where (year(getdate()) - year(p.Birthday)) % 3 = 0 and (year(getdate()) - year(p.Birthday))>=21 and (year(getdate()) - year(p.Birthday))<=99
	 and not exists
	(
		SELECT dd.* 
		FROM [RDS].T_DISP_DIRECT dd
			where dd.[ENP] = p.[ENP]
	)

	 select  @cnt = count(*)-@cnt from [RDS].T_DISP_DIRECT--Возвращаем сколько добавили записей
end