如何在SQL Server中创建字母序列?像A,B,C ...... Z,AA,AB ......我指的是这个 Given Letter, Get Next Letter in Alphabet链接,但在字母Z后它将无效。如何做到这一点?
答案 0 :(得分:4)
你可以使用算术。这将假设您在表中有数字(但是您想要生成它们):
select (case when (n / 26) % 27 = 0 then ''
else char(ascii('A') + (n / 26) % 27 - 1)
end) +
char(ascii('A') + n % 26)
from numbers n;
例如:
select (case when (n / 26) % 27 = 0 then ''
else char(ascii('A') + (n / 26) % 27 - 1)
end) +
char(ascii('A') + n % 26)
from (select top 100 row_number() over (order by (select null)) - 1 as n
from master..spt_values
) n;
Here是一个SQL小提琴。可以使用相同的逻辑生成更长的序列。
另一种方法是将一系列字母放在一起,然后只用cross join
将它们放在一起:
with letters as (
select top 26
char(ascii('A') + row_number() over (order by (select null)) - 1) as letter
from master..spt_values
)
select l1.letter as seq
from letters l1
union all
select l1.letter + l2.letter
from letters l1 cross join letters l2
union all
select l1.letter + l2.letter + l3.letter
from letters l1 cross join letters l2 cross join letters l3
order by len(seq), seq;
这有点挑战,因为序列的长度不同。
Here是一个说明这种方法的SQL小提琴。