我想制作一个算法,通过sql中指定的最后一个序列号生成下一个序列号,如下所示:
Last Number Next Number
> AAAA095 AAAA096
> AAAA999 AAAB001
> AAAB001 AAAB002
> AAAZ999 AABA001
答案 0 :(得分:1)
经过一番尝试,最后我得到了一个算法&为此问题创建SQL Scalar值函数,如下所示
CREATE FUNCTION GetNextSeries ( @lastSeriesNo VARCHAR(8))
RETURNS VARCHAR(8)
AS
BEGIN
DECLARE @nextSeriesNo VARCHAR(8)
DECLARE @CHAR1 CHAR=SUBSTRING(@lastSeriesNo,1,1)
DECLARE @CHAR2 CHAR=SUBSTRING(@lastSeriesNo,2,1)
DECLARE @CHAR3 CHAR=SUBSTRING(@lastSeriesNo,3,1)
DECLARE @CHAR4 CHAR=SUBSTRING(@lastSeriesNo,4,1)
DECLARE @n INT=SUBSTRING(@lastSeriesNo,5,3)
SET @n = @n + 1
IF(@n>999)
BEGIN
SET @n=1
IF(@CHAR4<>'Z')
BEGIN
SET @CHAR4=CHAR(UNICODE(@CHAR4)+1)
END
ELSE IF(@CHAR3<>'Z')
BEGIN
SET @CHAR4='A'
SET @CHAR3=CHAR(UNICODE(@CHAR3)+1)
END
ELSE IF(@CHAR2<>'Z')
BEGIN
SET @CHAR4='A'
SET @CHAR3='A'
SET @CHAR2=CHAR(UNICODE(@CHAR2)+1)
END
ELSE IF(@CHAR1<>'Z')
BEGIN
SET @CHAR4='A'
SET @CHAR3='A'
SET @CHAR2='A'
SET @CHAR1=CHAR(UNICODE(@CHAR1)+1)
END
END
SET @nextSeriesNo=@CHAR1+@CHAR2+@CHAR3+@CHAR4+(CASE LEN(@n) WHEN 1 THEN '00' WHEN 2 THEN '0' ELSE '' END)+convert(VARCHAR(3),@n)
RETURN @nextSeriesNo
END