简体   繁体   中英

Oracle 12c SQL Random String Digits Only Size 10

what's the easiest way to get a 10 character random string containing only numeric characters (digits)? The one below gives something similar but I would like to get strings with left padded zeros also. eg 0000000020

SELECT LPAD(REPLACE(TO_CHAR(dbms_random.value(1, 9999999999)),'.',''),10,'0') randomnumstr 
  FROM dual;

Break it down in pieces...

select to_char(dbms_random.value(1, 10000000000), 'FM0000000000') from dual;

First, the dbms_random.value will return a number in the range [a,b), so use 1 as the start and 10000000000 as the end. The number will never equal 10000000000.

Second, use TO_CHAR with a mask of FM0000000000 . The FM removes the padding added for the sign. By not including a decimal point, the fractional portion of the random number is truncated.

DBMS_RANDOM.VALUE docs

Now test a few literals to make sure it works:

select to_char(1.234, 'FM0000000000') from dual;

0000000001

select to_char(1234, 'FM0000000000') from dual;

0000001234

select to_char(1234567890, 'FM0000000000') from dual;

1234567890

-- Now make sure there are no spaces for the sign
select length(to_char(123, 'FM0000000000')) from dual;

10

This might be a shorter choice :

SELECT DECODE(val,0,val+1E-10,val) AS randomnumstr 
  FROM
  (SELECT SUBSTR(DBMS_RANDOM.VALUE(0, 1),-10) AS val
     FROM dual);  

which may also contain preceding zeroes and having ten-digit-length. The val is generated as being greater than or equal to 0 , and strictly less than 1 ( 0<=val<1 ). In the case, val equals to 0 , then result will be 0000000001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM