1

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;

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

This is at least an order of magnitude faster. +1
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.