sqloracle-databaseoracle10goracle11gr2

How to generate alphabetic letters between 2 values in oracle sql?


select 'V4A-V4G' FROM DUAL;

sample output:

    V4A
    V4B
    V4C
    V4D
    V4E
    V4G

select 'R8M-R8S' FROM DUAL;

sample output:

    R8M
    R8N
    R8O
    R8P
    R8Q
    R8R
    R8S

Solution

  • A more direct way (avoiding the CONNECT BY process):

    with
      test (id, col) as (
        select 1, 'V4A-V4G' from dual union all
        select 2, 'R8M-R8S' from dual
      )
    select id, substr(col, 1, 2) || column_value as val
    from   test join sys.odcivarchar2list('A','B','C','D','E','F','G','H','I',
           'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
           on column_value between substr(col, 3, 1) and substr(col, 7, 1)
    order  by id, val  --  if needed
    ;
    

    Of course, if you need to do this often, you can use an actual table with one column and 26 rows holding the capital letters, so you won't need to create it on the fly in every query that uses it (and every time the query is used). That would make the query that much simpler still.

    Note - in older Oracle versions you may need to wrap sys.odci...list within table( ... ).