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


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

-- =============================================
-- Description: Обновить список по диспансеризации за текущий year(getdate()) год
-- =============================================
CREATE PROCEDURE [RDS].[sp_DispFactLink]
(
    @cnt INTEGER OUTPUT
)
as
begin
	declare @cnt int
	set @cnt = (select count(*) from [RDS].T_DISP_DIRECT_FACT where DispDirect is null)

	update fact
	set fact.DispDirect = (select top 1 dd.DispDirectID 
							FROM [RDS].T_DISP_DIRECT dd 
							WHERE (fact.FAM = dd.FAM and fact.IM = dd.IM and fact.OT = dd.OT and fact.DR = dd.DR and Stage = 0) 
								or (fact.FAM = dd.FAM and fact.OT = dd.OT and fact.DR = dd.DR and Stage = 0)
								or (fact.FAM = dd.FAM and fact.IM = dd.IM and fact.DR = dd.DR and Stage = 0)
								or (fact.IM = dd.IM and fact.OT = dd.OT and fact.DR = dd.DR and Stage = 0)
	)
	from [RDS].[T_DISP_DIRECT_FACT] fact
	where fact.DispDirect is null



	 select @cnt = @cnt - count(*) from [RDS].T_DISP_DIRECT_FACT where DispDirect is null--Возвращаем сколько фактов нашли
end