Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

database - is it possible to have alphanumeric sequence generator in sql

I need to write a SQL query to print the following aphanumberic sequence in SQL

0001, 0002, ... , 0009, 000A, ... , 000Z, ... , 0010, 0011, ... , 001A, ... and so on till... , ZZZZ

please note: all characters are UPPERCASE.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could create a function like this:

create function to_base_36 (n integer) return varchar2
is
  q integer;
  r varchar2(100);
begin
  q := n;
  while q >= 36 loop
     r := chr(mod(q,36)+case when mod(q,36) < 10 then 48 else 55 end) || r;
     q := floor(q/36);
  end loop;
  r := chr(mod(q,36)+case when mod(q,36) < 10 then 48 else 55 end) || r;
  return lpad(r,4,'0');
end;

and then use it like this:

select rownum, to_base_36(rownum)
from dual
connect by level < 36*36*36*36;

Or, without creating a function:

with digits as
( select n, chr(mod(n,36)+case when mod(n,36) < 10 then 48 else 55 end) d
  from (Select rownum-1 as n from dual connect by level < 37)
)
select d1.n*36*36*36 + d2.n*36*36 + d3.n*36 + d4.n, d1.d||d2.d||d3.d||d4.d
from digits d1, digits d2, digits d3, digits d4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...