我必须按字母顺序生成ID。
假设现有ID为- A
因此,我必须检查现有的最大字母,然后再生成。
像下一个意志-B ,依此类推。
所以我已经从A生成到Z。
但是在“ Z”之后,还需要再次生成AA,AB等。
我尝试使用以下查询-
SELECT REGEXP_SUBSTR(CHR(ASCII(TRIM (REGEXP_SUBSTR ('Z_2203','[^_]+')))+1),'[A-Za-z]') FROM DUAL;
来自评论的示例数据:
Present_id
A_2004
B_2004
C_2004
'
'
'
Z_2004
预期结果-
B
C
D
'
'
'
AA
AB
答案 0 :(得分:2)
您可以使用以下递归函数:
create or replace function alpha_id(i_id in varchar2) return varchar2 is
begin
if trim(translate(i_id, 'Z', ' ')) is null then
return rpad('A', nvl(length(i_id), 0) + 1, 'A');
end if;
if substr(i_id, length(i_id), 1) = 'Z' then
return alpha_id(substr(i_id, 1, length(i_id) - 1))||'A';
else
return substr(i_id, 1, length(i_id) - 1)
|| chr(ascii(substr(i_id, length(i_id), 1)) + 1);
end if;
end alpha_id;
这里特别注意,如果最后一个字符为Z
,则只需对字符串进行操作并进行递归调用。测试:
with t(rn, id) as (
select 1, 'A' from dual union all
select 2, 'N' from dual union all
select 3, 'Z' from dual union all
select 4, 'AA' from dual union all
select 5, 'BP' from dual union all
select 6, 'QZ' from dual union all
select 7, 'ZZ' from dual union all
select 8, 'BPZ' from dual union all
select 9, 'ZZZ' from dual )
select rn, id, alpha_id(id) next_id from t;
结果:
RN ID NEXT_ID
----- --- ---------
1 A B
2 N O
3 Z AA
4 AA AB
5 BP BQ
6 QZ RA
7 ZZ AAA
8 BPZ BQA
9 ZZZ AAAA
答案 1 :(得分:0)
这将起作用:
SELECT * FROM D061_WORDS;
A_2004
B_2004
Z_2004
select case when ascii(chr(ascii(substr(a,1,1))+1))<=ascii('Z') then
chr(ascii(substr(a,1,1))+1) when ascii(chr(ascii(substr(a,1,1))+1))>=ascii('Z') then
'A'||chr(ascii(chr(ascii(substr(a,1,1))+1))-26) end from D061_WORDS;
B
C
AA