do $$
declare
    adr_klad record;
    p_error_code varchar = null;
    p_error_message varchar = null;
begin	
CREATE INDEX IF NOT EXISTS idx_tmp_gpp_kladr_street_code ON tmp.gpp_kladr_street USING btree (code);
/*
while (
		select count(1) from tmp.gpp_kladr_street t
		where not exists (select 1 from dbo.klstreet k where k.kladr_code=t.code)
		and right(t.code, 2) = '00'
		)>0
		LOOP
*/
		for adr_klad in		
				select 
						trim(upper(name)) as klstreet_name,
						trim(upper(socr)) as klsocr_nick,
						code::varchar(20) as klstreet_code,
						case when trim(index::varchar(10))='' then null 
						 else trim(index::varchar(10))
						 end as klstreet_index,
						gninmb::varchar(20) as klstreet_gninmb,
						case when trim(uno::varchar(10))='' then null 
								 else trim(uno::varchar(10))
								 end as klstreet_uno,
						ocatd::varchar(20) as klstreet_ocatd
				from tmp.gpp_kladr_street t
				where not exists (select 1 from klstreet k where k.kladr_code=t.code)
				and right(t.code, 2) = '00'
				--limit 5000
			LOOP
	
				select fnc.error_code, fnc.error_message 
				into p_error_code, p_error_message
				from dbo.xp_klstreet_ins(
					klstreet_name := adr_klad.klstreet_name,
					klsocr_nick := adr_klad.klsocr_nick,
					klstreet_code := adr_klad.klstreet_code,
					klstreet_index := adr_klad.klstreet_index,
					klstreet_gninmb := adr_klad.klstreet_gninmb,
					klstreet_uno := adr_klad.klstreet_uno,
					klstreet_ocatd :=adr_klad.klstreet_ocatd
				)fnc;		
	
			end loop;
			--exit;
--		end LOOP;
	exception when others then
		raise notice ' Ошибка: %', SQLSTATE; 
		raise notice ' Ошибка: %', SQLERRM;

end $$
