Random integer in a range

From PostgreSQL wiki

(Difference between revisions)
Jump to: navigation, search
 
Line 1: Line 1:
 
{{SnippetInfo|Random integer in a range|lang=PL/Perl}}
 
{{SnippetInfo|Random integer in a range|lang=PL/Perl}}
 
by Emanuel '3m4nuek' CF
 
  
 
<source lang="perl">
 
<source lang="perl">
Line 31: Line 29:
  
  
 +
- 3manuek
 
[[Category:PL/Perl]]
 
[[Category:PL/Perl]]

Latest revision as of 10:41, 5 April 2012

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