function for creating random id

From: Moritz Sinn <moritz(at)freesources(dot)org>
To: pgsql-general(at)postgresql(dot)org
Subject: function for creating random id
Date: 2002-04-15 15:51:53
Message-ID: m3sn5xarja.fsf@freesources.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

hi,

i've got a table called "user". every user should have a userid, which
is the primary key. this userid is a random number with up to 6 digits.

to get this userid i wrote a function in plpgsql:

CREATE FUNCTION getuid(int) RETURNS int AS '
DECLARE
uid INTEGER;
BEGIN
SELECT (random() * (pow(10.0, $1::float)-1))::int INTO uid;
RETURN uid;
END;' LANGUAGE 'plpgsql' WITH (isstrict);

user was created with:

CREATE TABLE "user" (id numeric(6,0) DEFAULT getuid(6), username
VARCHAR(20), password VARCHAR(20), name VARCHAR(30), forename
VARCHAR(30), CONSTRAINT "user_pk" PRIMARY KEY("id"));

but now the problem is that the id which is returned by getuid() could
already be in use.
so what is the best method to realize that?
i mean isn't there already a function which returns a boolean, saying if
this id is already in use or not?

thanks,
moritz

--
Subject: Linux box finds it hard to wake up in the morning

I've heard of dogs being like their owners, but Linux boxen?
-- Peter Hunter <peter(dot)hunter(at)blackfriars(dot)oxford(dot)ac(dot)uk>

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Moritz Sinn 2002-04-15 16:19:59 string encryption
Previous Message Michael Loftis 2002-04-15 15:16:38 Re: Why does postgres not take into account my index on a bigint column ?