Monday, June 25, 2018

How to Create alphanumeric sequence in sql

To create an alphanumeric sequence like this:


AAAA0000
AAAA0001
AAAA0002
AAAA0003
.
.
.
AAAA9999
AAAB0000
AAAB0001
.
.
.
ZZZZ9999


spAlphaNumericIDGeneration  will return next alphanumeric number.


tblItinerary  :  table Name
TagName    :  fileld Name

CREATE PROCEDURE spAlphaNumericIDGeneration
AS
declare
@alphabet varchar(4),
@number int,
@alphanumeric varchar(6),
@strNumber varchar(6),
@strAlphabet varchar(6),
@strAlphaNumeric varchar(7),
@Year varchar(4),
@intYear int

BEGIN

select @alphanumeric=max(TagName) from tblItinerary  
if @alphanumeric=''
BEGIN
 set @alphanumeric='AAA000'
END
set @alphabet=SUBSTRING(@alphanumeric,1,3)
set @number=SUBSTRING(@alphanumeric,4,3)

select @Year=Datepart(YEAR,getdate())
set @intYear=SUBSTRING(@Year,3,2)


if @number=999
BEGIN
 set @number=1

;WITH
Tens     (N) AS (SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL
                 SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL
                 SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0),
Thousands(N) AS (SELECT 1 FROM Tens t1 CROSS JOIN Tens t2 CROSS JOIN Tens t3),
Millions (N) AS (SELECT 1 FROM Thousands t1 CROSS JOIN Thousands t2),
Tally    (N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM Millions),
CTE1     (A) AS (SELECT CHAR(N+64) FROM Tally WHERE N between 1 and 26),
CTE2     (B) AS (SELECT c1.A + c2.A FROM CTE1 c1 CROSS JOIN CTE1 c2),
CTE3     (C) AS (SELECT c1.A + c2.A + c3.A FROM CTE1 c1 CROSS JOIN CTE1 c2 CROSS JOIN CTE1 c3),
CTE4     (D) AS (SELECT c1.A + c2.A + c3.A + c4.A FROM CTE1 c1 CROSS JOIN CTE1 c2 CROSS JOIN CTE1 c3 CROSS JOIN CTE1 c4),
CTE          AS (SELECT A, RN = 1 FROM CTE1 UNION ALL
                 SELECT B, RN = 2  FROM CTE2 UNION ALL
                 SELECT C, RN = 3  FROM CTE3 UNION ALL
                 SELECT D, RN = 4 FROM CTE4)

 SELECT  top 1 @strAlphabet = A FROM CTE WHERE  RN =3 and  A > @alphabet order by A
END
ELSE
BEGIN
 set @number=@number+1
 set @strAlphabet = @alphabet
END
set @strNumber=right(replicate('0',3)+cast(@number as varchar(15)),3)

set @strAlphaNumeric=ltrim(rtrim(@strAlphabet)) + ltrim(rtrim(@strNumber)) + Char(64 +@intYear)

Select @strAlphaNumeric As ID
END