Random integer in a range

From PostgreSQL wiki

Jump to: navigation, search

Snippets

Random integer in a range

Works with PostgreSQL

Any version

Written in

PL/Perl

Depends on

Nothing


CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer 
LANGUAGE plperl IMMUTABLE RETURNS NULL ON NULL INPUT
AS $pg_round_random_range$
	my($imin, $imax) = @_;	
	if ($_[0] == $_[1]){
		return $_[0];	}
	if($imin > $imax){
		$imin = $_[1];
		$imax = $_[0];	}	
	$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
        return sprintf "%d",$_number_;
$pg_round_random_range$;


If you don't want to control the arguments:

CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer 
LANGUAGE plperl IMMUTABLE RETURNS NULL ON NULL INPUT
AS $pg_round_random_range$
   my($imin, $imax) = @_;	
   $_number_ = $imin + ( (rand) * ($imax -$imin + 1));
   return sprintf "%d",$_number_;
$pg_round_random_range$;


- 3manuek

Personal tools