DO $script$
declare
	p_person_id bigint;
	mcurs refcursor;
BEGIN
CREATE table if not EXISTS tmp.gpp_89761_personcardstate_20211207 as 
		select person_id from dbo.personcardstate where personcard_id in (select personcard_id from dbo.personcard where personcard_deleted=2); 

alter table tmp.gpp_89761_personcardstate_20211207 add column if not exists isupdate bigint null;

IF (dbo.getregion()=89 and current_database()='promed') or current_database()='promedtest'
THEN
		open mcurs for
				select person_id from dbo.personcardstate where personcard_id in (select personcard_id from dbo.personcard where personcard_deleted=2)
						and person_id not in (select person_id from tmp.gpp_89761_personcardstate_20211207 where isupdate=2) limit 5000 ;
					loop fetch mcurs into p_person_id;
					exit when not found;
				perform fnc.* from dbo.xp_update_personcardstate(person_id:=p_person_id, lpuattachtype_id:=null)fnc;
				
				update tmp.gpp_89761_personcardstate_20211207	set isupdate=2	where person_id=p_person_id;
				
		end loop;
	
END IF;

END $script$
