Generate Upper and Lowercase Alphanumeric Random String in Oracle

前端 未结 6 645
北荒
北荒 2021-02-05 14:55

How does one generate an upper and lowercase alphanumeric random string from oracle?

I have used select DBMS_RANDOM.STRING(\'x\', 10) from dual to generate

6条回答
  •  无人共我
    2021-02-05 15:23

    You can make your own function. This is one option:

    create or replace function random_str(v_length number) return varchar2 is
        my_str varchar2(4000);
    begin
        for i in 1..v_length loop
            my_str := my_str || dbms_random.string(
                case when dbms_random.value(0, 1) < 0.5 then 'l' else 'x' end, 1);
        end loop;
        return my_str;
    end;
    /
    
    select random_str(30) from dual;
    
    RANDOM_STR(30)
    --------------------------------------------------------------------------------
    pAAHjlh49oZ2xuRqVatd0m1Pv8XuGs
    

    You might want to adjust the 0.5 to take into account the different pool sizes - 26 for l vs. 36 for x. (.419354839?). You could also use value() and pass in the start and end range of the character values, but that would be character-set specific.

    As to why... do Oracle need a reason? The use of x might suggest that it was originally hexadecimal and was expanded to include all upper-case, without it occurring to them to add a mixed-case version at the same time.

提交回复
热议问题