-- 423 434
DO
LANGUAGE plpgsql
$$
DECLARE
  _ss varchar(40);
  _person_id bigint;
  p_error_code varchar = null;
  p_error_message varchar = null;
  cur cursor for 
	SELECT -- count(DISTINCT tmp.person_id)
	DISTINCT tmp.ss, tmp.person_id -- tmp.ss, vps.Person_snils, tmp."FIO", vps.Person_Surname, vps.Person_Firname, vps.Person_Secname, tmp.dr, vps.Person_Birthday, tmp."N_POL", vps.Polis_num, vps.Person_EdNum
	from tmp.fvv_promedweb_95766_import tmp
	inner join v_personstate vps on vps.Person_id = tmp.Person_id
	left join (select DISTINCT ti.person_id from tmp.fvv_promedweb_95766_IsNotUse12 tn
					inner join tmp.fvv_promedweb_95766_import ti  ON ti.person_id = tn.person_id
					inner join tmp.fvv_promedweb_95766_import ti2 ON ti2.person_id = ti.person_id AND	(trim(ti.ss) <> trim(ti2.ss))
					WHERE ti.IsNotUse is null AND ti.CauseNotUse IS NULL AND ti2.IsNotUse is null AND ti2.CauseNotUse IS NULL) twink on twink.person_id = tmp.person_id
	WHERE tmp.Person_id IS NOT NULL
		AND tmp.ss IS NOT NULL
		AND tmp.IsNotUse IS NULL
		AND tmp.CauseNotUse IS NULL
		AND coalesce(vps.Person_snils,'999888777001112') <> tmp.ss
		AND twink.person_id is null
	limit 1000;
	
BEGIN
  OPEN cur; 
  LOOP
  FETCH cur into _ss,_person_id;
  EXIT WHEN NOT FOUND;
	UPDATE tmp.fvv_promedweb_95766_import tmp2 set IsNotUse = 1000, CauseNotUse = 1000 where tmp2.Person_id = _person_id; 
	
	select fnc.error_code, fnc.error_message
	into p_error_code, p_error_message
	from dbo.p_PersonSnils_ins(
		server_id:=0,
		person_id:=_person_id,
		personsnils_snils:=_ss,
		pmuser_id:=1
		)fnc;	
	
	raise notice 'СНИЛС person_id = % error=%', _person_id, p_error_message;
  END LOOP;	
  CLOSE cur;	
END;
$$
