if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_DirectDispancerRDSDelete]') and xtype = N'P')
DROP PROCEDURE  [dbo].[sp_DirectDispancerRDSDelete]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Vitacore (с)
-- Create date: 2017-11-01
-- Description: Удалить список пациентов, направляемых на текущюю диспансеризацию
-- =============================================
CREATE PROCEDURE [dbo].[sp_DirectDispancerRDSDelete]
	@RdsdispPackageID uniqueidentifier
	
AS

BEGIN
	SET NOCOUNT ON;
	
	update base
	set base.ClinicExaminationItem = null
	from AKUZ.T_EXAMINATION_BASE base
	join AKUZ.T_CLINIC_EXAMINATION_ITEM item on base.ClinicExaminationItem = item.ClinicExaminationItemID
	join AKUZ.T_RDS_DISP_PATIENT pat on pat.RdsDispPatientID = item.RdsDispPatient
	join AKUZ.T_RDS_DISP_PACKAGE pack on pack.RdsdispPackageID = pat.RdsDispPackage
	where pack.RdsdispPackageID = @RdsdispPackageID

	delete item
	from AKUZ.T_CLINIC_EXAMINATION_ITEM item
	join AKUZ.T_RDS_DISP_PATIENT pat on pat.RdsDispPatientID = item.RdsDispPatient
	join AKUZ.T_RDS_DISP_PACKAGE pack on pack.RdsdispPackageID = pat.RdsDispPackage and pat.RdsDispPackage = @RdsdispPackageID
	
	delete 		
	from [AKUZ].T_RDS_DISP_PATIENT
	where RdsDispPackage in (select pk.RdsdispPackageID from AKUZ.T_RDS_DISP_PACKAGE pk where pk.RdsdispPackage = @RdsdispPackageID)

	delete
    from [AKUZ].T_RDS_DISP_PATIENT 
	where RdsdispPackage =  @RdsdispPackageID

	delete
	from [AKUZ].T_RDS_DISP_PACKAGE
	where RdsdispPackage = @RdsdispPackageID

	delete
    from [AKUZ].T_RDS_DISP_PACKAGE
	where RdsdispPackageID = @RdsdispPackageID

END

go