SQL,它在给定的起点和终点之间生成字母序列

时间:2015-05-08 11:19:09

标签: sql oracle

我需要一个SQL,它在给定的起点和终点之间生成字母序列。

喜欢,Start='C' End='G'输出应为

C
D
E
F
G 

3 个答案:

答案 0 :(得分:6)

select chr(ascii('C') + level - 1) 
from dual
connect by ascii('C') + level - 1 <= ascii('G');

使用这样的connect by(没有start with和仅取决于级别的结束条件)没有记录(并且不受支持),所以它可能会随时中断(尽管我不知道任何时间)这不起作用的版本。)

从11.2开始,您还可以使用递归公用表表达式:

with letters (letter, inc) as (
   select 'C', 1 as inc
   from dual
   union all
   select chr(ascii('C') + p.inc), p.inc + 1
   from letters p
   where p.inc < 5
)
select letter
from letters;

答案 1 :(得分:0)

像这样的东西

WITH X AS
(SELECT 'C' as St, 'G' as En FROM dual)
SELECT CHR(ASCII(X.St)+ROWNUM-1)
FROM X
CONNECT BY ROWNUM<=(ASCII(X.En)-ASCII(X.St)+1)

答案 2 :(得分:0)

修改@a_horse_with_no_name回答如下

WITH X(lettr) AS 
(SELECT 'C' lettr FROM DUAL
 UNION ALL
 SELECT CHR(ASCII(X.lettr)+1) letter
 FROM X 
 WHERE ASCII(X.lettr)<ASCII('G'))
 SELECT * FROM X