drop procedure if exists public.sp_SetCAMIStudyCard;
-- =============================================
-- Author:		Aidar R. Salikhov
-- Create date: 2014/07/17
-- Description:	Связыввает изображения из ЦАМИ с Амбулаторной картой
-- =============================================
CREATE procedure public.sp_SetCAMIStudyCard
(
	"LpuCode" varchar(6) = null,
	"CardNumber" varchar(32) = null,
	"StudyID" UUID = null
)
AS
$$
BEGIN
	if "CardNumber" is not null and "LpuCode" is not null and "StudyID" is not null
	then
		update akuz.T_CAMI_STUDY
		set AmbulanceCard = 
		(
			select t1.AmbulanceCardID 
			from akuz.T_Ambulance_Card t1
			inner join 
				akuz.T_LPU_MAIN t2 
				on t1.cardlpu = t2.lpuid
			where t1.number = "CardNumber"
			and t2.lpucode = "LpuCode"
			limit 1
		)
		where CAMIstudyid = "StudyID";
	end if;

END;
$$ LANGUAGE plpgsql;