CREATE OR REPLACE FUNCTION sp_GenerateCouponsNumber("gen_count" int)
  RETURNS int AS
$BODY$
declare _rc int; _rowcount int;
	_max int;
Begin
	_rc := 0;
	_max := coalesce((select MilkCouponsIdID from AKUZ.T_MILK_COUPONS_ID order by milkcouponsidid desc limit 1 for update), 0);
	while _rc <> "gen_count"
	loop
		insert into AKUZ.T_MILK_COUPONS_ID(MilkCouponsIdID, Id, CreateDate)
		select distinct  
		  row_number() over (order by (select null)) + _max
		, t.x
		, now()::timestamp
		from
		(
			select right('000000000000' || ltrim(('x' || translate(uuid_generate_v4()::varchar(36), '-', ''))::bit(64)::bigint::varchar(12), '-'), 12) as x
			from pg_class pc
			limit 1000
		) t
		where not exists(select * from AKUZ.T_MILK_COUPONS_ID tt where tt.Id = t.x)
		limit ("gen_count" - _rc);
		GET DIAGNOSTICS _rowcount = ROW_COUNT;
		_rc := _rc + _rowcount;
	end loop;	
	return _max + 1;
End;
$BODY$
  LANGUAGE plpgsql VOLATILE;
ALTER FUNCTION sp_GenerateCouponsNumber(int)
  OWNER TO postgres;