Re: Random Number Generation
Posted in 1996
Joseph Kormann (jkormann@castle.net) wrote:
: >Does anyone know of a SQL function/routine to generate random numbers,
: >or of a basic RNG algorithm that could be coded in SQL. Just want to
: >generate a random number between 1 and x.
Try this;
Note that this isn't exactly the right thing to do for IUS, but
I think it should work. The idea is that you need to 'seed' the
random number generator, but that this should be done only once. I
As a general strategy, using globals in this way is a very, very bad
idea. (Thread-safety and all that.)
#include <mi.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
int IsSeeded = 0;
mi_integer random( mi_integer nMax )
{
extern int IsSeeded;
if (!IsSeeded)
{
IsSeeded = 1;
(void)srand((unsigned int)time((time_t *)NULL));
}
return (mi_integer)((rand()%nMax) + 1);
}
--
-- This is the thing which declares the function
--
DROP FUNCTION Rand(integer);--
CREATE FUNCTION Rand(integer)RETURNS integer
AS EXTERNAL NAME 'MI_HOME/functions/Rand.so(random)'
LANGUAGE C;
--
RETURN Rand(10);
--
SELECT Rand(A)
FROM {5,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10}::setof(integer) A;
--
=====================================================================
Paul Brown ^..^
pbrown@postgres.Berkeley.EDU (oo) - Oink!
#include <std_disclaimer.h>
"Think global - act loco!" - Zippy the Pinhead
=====================================================================