Random function/Sequence like field

Hi,

I am trying to figure out the best way to create a field that contains a randomly generated string.  I'm currently using a sequence as a test for this field.  I'd like to make this a bit more secure by adding a randomly generated 16 character string.  I'm not sure how I would do this in plpgsql language. Any suggestions ?  Thanks!
windows_programingAsked:
Who is Participating?
 
earth man2Connect With a Mentor Commented:
create or replace function random_string( size in integer ) returns text as $$
declare
  s  text := '';
  idx int := 1;
begin

  while (  idx < size ) loop

    s := s || chr( floor( random() * ( ascii('z') - ascii('a') ) + ascii('a') )::int );

    idx := idx + 1;

  end loop;

  return s;
end;
$$ language plpgsql;


=> select random_string(10);
 random_string
---------------
 kemaprluc
(1 row)
0
 
m1tk4Connect With a Mentor Commented:
using the random() funciton:

select  select chr((random()*25)::int+97)||chr((random()*25)::int+97) ;

for example will produce random 2-character strings using characters a (ASCII 97) to z (ASCII 122 ( = 97+25)). Just type it 14 times more to get a 16 characters;)
0
 
windows_programingAuthor Commented:
Thanks!

I like earthman2's function that allows me to specify the number of random characters.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.