DO $script$
declare
	p_personcard_id bigint;
	p_person_id bigint;
	mcurs refcursor;
BEGIN

IF (dbo.getregion()=89 and current_database()='promed')
THEN
		open mcurs for
			select personcard_id, person_id from v_personcard where lpu_id=13101870 ;-- limit 65;
				loop 
					fetch mcurs into p_personcard_id, p_person_id;
				exit when not found;

				if not EXISTS (select 1 from dbo.personcard where personcard_id = p_personcard_id and COALESCE(personcard_deleted,0)=2)
					then
						update dbo.personcard
						set personcard_deleted=2,
						personcard_deldt=now(),pmuser_delid=1 
						where personcard_id = p_personcard_id;					
					end if;
					
				update dbo.personcard
				set personcard_enddate=personcard_deldt,
				pmuser_updid=1, personcard_upddt=now()
				where personcard_id = p_personcard_id;		

				if EXISTS (select 1 from dbo.personstate where person_id=p_person_id and lpu_id=13101870 limit 1)
					THEN
						update dbo.personstate
						set lpu_id=null,
						pmuser_updid=1, personstate_upddt=now()
						where person_id = p_person_id;
					end if;
				PERFORM fnc.* from dbo.xp_update_personcardstate(person_id:=p_person_id, lpuattachtype_id:=null)fnc;		
		end loop;
END IF;
END $script$
