plpgsql function to generate random readable strings

I have written the following function but it's isn't returning anything when I run it. Can somebody help identify the issue?

CREATE OR REPLACE FUNCTION GenerateReadableRandomString (
len INT
) RETURNS varchar AS
$$
DECLARE
validchars VARCHAR;
randomstr VARCHAR;
randint INT;
i INT;

BEGIN

validchars := 'ABCEFHJKLMNPRTWXY3478';
i := 0;

LOOP
    randint := ceil(random() * char_length(validchars));
    randomstr := randomstr || substring(validchars from randint for 1);
    i := i + 1;
    EXIT WHEN i = len;
END LOOP;

RETURN randomstr;
END;
$$
LANGUAGE plpgsql;

Answers


Yeah the problem is that you haven't initialized your variable randomstr. And when you concat something with null you get null


faster code can be

CREATE OR REPLACE FUNCTION rstr(int)
RETURNS text AS $$
SELECT array_to_string(ARRAY(SELECT substring('ABCEFHJKLMNPRTWXY3478' FROM (random()*21)::int + 1 FOR 1) 
                                FROM generate_series(1,$1)),
                       '') 
$$ LANGUAGE sql;

Need Your Help

VB.net decrypt rinjdael-128 encrypted string

encryption aes vb.net-2010

I am writing a VB.Net app that reads and decrypts the response from a JSON web service. I have the secret passphrase and I am able to decrypt the encrypted string without a problem using online

Polling a semaphore multiple times simultaneously using posix C

c multithreading posix semaphore

This question requires that two semaphores be used, one as a mutex, and one as a counting semaphore, and that the pair be used to simulate the interaction between students and a teacher's assistant...