我已经编写了以下函数,但是当我运行它时它没有返回任何内容。有人可以帮助确定问题吗?
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;
答案 0 :(得分:2)
更快的代码可以
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;
答案 1 :(得分:1)
是的问题是你没有初始化你的变量randomstr。当你用null结束某些东西时你会得到null