drop procedure if exists public.sp_SetSNILS;
CREATE procedure public.sp_SetSNILS
(
	"PatientID" UUID = null
)
AS
$$
BEGIN
	if "PatientID" is not null
	then
		update akuz.T_PATIENT p
		set SNILS = f.Snils
		from akuz.T_FR_PATIENT f
		where p.FirstName = f.FirstName
		and p.LastName = f.LastName
		and p.FatherName = f.FatherName
		and p.Birthday = f.Birthday
		and p.PatientID = "PatientID";
	else
		update akuz.T_PATIENT p
		set SNILS = f.Snils
		from akuz.T_FR_PATIENT f
		where p.FirstName = f.FirstName
		and p.LastName = f.LastName
		and p.FatherName = f.FatherName
		and p.Birthday = f.Birthday;
	end if;
	update akuz.T_FR_RECORD 
	set DateEnd = null 
	where DateEnd < '1900-01-01';
	update akuz.T_FR_RECORD 
	set DateNsuEnd = null 
	where DateNsuEnd < '1900-01-01';
END;
$$ LANGUAGE plpgsql;