I need to generate a 3 character alphanumeric sequence, in SQL Server 2008, as follows:
001,
002,
...,
999,
A01,
A02,
...,
A99,
B01,
B02,
...,
Z99
The next item in the sequence will get generated from a stored procedure and stored in a NCHAR(3)
table column.
To get the next sequence you can add a Id
like
WITH seq AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY x.alpha + y.number + z.number) AS Id,
CONVERT(nchar(3), x.alpha + y.number + z.number) AS Result
FROM
(
VALUES
('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9'),
('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')
) x(alpha),
(
VALUES
('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9')
) y(number),
(
VALUES
('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9')
) z(number)
WHERE
NOT (NOT x.alpha BETWEEN '1' AND '9' AND y.number = '0' AND z.number = '0')
)
-- Uncomment to see all results
--SELECT * FROM seq
SELECT Result FROM seq WHERE Id = (SELECT Id + 1 FROM seq WHERE Result = 'Z01')
Result
Z02
Full count = 3573 = 999 + (26 * 99)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With