if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_UpdateStateAmbulanceCard]') and xtype = N'P')
drop procedure [dbo].[sp_UpdateStateAmbulanceCard]
GO
-- =============================================
-- Author:		Vitacore
-- Create date: 2023/08/15
-- Description:	Процедура апдейтит поля у AMBULANCE_CARD State 
-- =============================================
create PROCEDURE [dbo].[sp_UpdateStateAmbulanceCard] 
   @PatientID uniqueidentifier -- Идентификатор PATIENT
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET XACT_ABORT, NOCOUNT ON;

	declare @StateID uniqueidentifier, @LpuID uniqueidentifier, @Status int

	select top 1 @StateID = r.State, @LpuID = r.LpuMain, @Status = r.Status
	from [AKUZ].T_REGISTRATION r with(nolock)
	where r.Patient = @PatientID and r.RegistrationDate <= getdate() and r.[AttachmentStatus] > 0
		AND (r.[Profile] in (1,2))
	order by RegistrationDate desc

   update ac
	set ac.State = (case when @Status = 1 and @LpuID = ac.CardLpu then @StateID else null end)
	from AKUZ.T_AMBULANCE_CARD ac
	where ac.Patient = @PatientID
END