do $$
declare

    mcurs refcursor;
    p_person_id bigint;
    p_snils varchar(11);
    p_server_id bigint:=101;
    p_pmuser_id bigint:=1;
    p_error_code varchar = null;
    p_error_message varchar = null;
begin
				open mcurs for
					select ps.person_id, l.snils
					from v_personstate ps
					inner join public.psv_PROMEDWEB52833_20210412_personlgot l on l.person_id=ps.person_id
					where (l.snils is not null and l.snils<>'' and l.snils<>'00000000000') 
					and coalesce(ps.person_snils,'') ='' and length(l.snils)=11 and dbo.isnumeric(l.snils)=1
					;

				loop fetch mcurs into
						p_person_id, p_snils;

				exit when not found;

						select fnc.error_code, fnc.error_message
						into p_error_code, p_error_message
						from dbo.p_personsnils_ins(
								server_id:=p_server_id,
								person_id:=p_person_id,
								personsnils_snils:=p_snils,
								pmuser_id:=p_pmuser_id
						)fnc;

					--raise notice 'person_id = % ', p_person_id;
				end loop;
				close mcurs;
end $$;
 
 
/*
select ps.*
from v_personstate ps
inner join public.psv_PROMEDWEB52833_20210412_personlgot l on l.person_id=ps.person_id
where coalesce(ps.person_snils,'') =''
*/ 