【问题标题】:Generating next alphabetical sequence from given alphabet in oracle从oracle中的给定字母生成下一个字母序列
【发布时间】:2019-05-14 18:02:53
【问题描述】:

我必须按字母顺序生成 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

【问题讨论】:

  • 添加一些示例表数据和预期结果。 (全部为格式化文本,而不是图像。)
  • 样本表:- 输入数据Present_id A_2004 B_2004 . Z_2004Expected Result- B C . AA
  • Present_id A_2004 B_2004 。 Z_2004 预期结果 - B C。 AA个人是吗??
  • 在 "Z" 之后应该给出 AA ,然后是 AB,AC 像这样。
  • 在为时已晚之前停止它并使用数字序列!

标签: sql oracle plsql oracle11g plsqldeveloper


【解决方案1】:

你可以使用类似这样的递归函数:

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

【讨论】:

    【解决方案2】:

    这将起作用:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 2012-02-01
      相关资源
      最近更新 更多