增加一个alpha字符串

时间:2016-03-17 13:49:33

标签: sql-server tsql

我正在使用一串字符,我需要定期增加到下一个字母。

如果信件超过z,则需要添加另一个“数字”,例如:

  • a => B'/ LI>
  • b => c
  • z => AA
  • aa => AB
  • az => BA
  • zz => AAA

...等

有一个函数来执行此操作非常有用。

2 个答案:

答案 0 :(得分:0)

这是我的解决方案:

CREATE FUNCTION dbo.IncrementString
(
    @String varchar(10)
)
RETURNS varchar(10)
AS
BEGIN

    DECLARE @LastChar   char,
            @Remainder  varchar(50)

    SELECT  @LastChar   = RIGHT(@String, 1)
    IF      LEN(@String) > 1
            SELECT      @Remainder  = LEFT(@String, LEN(@String)-1 )
    ELSE
            SELECT      @Remainder  = ''

    IF      @LastChar   NOT BETWEEN 'a' AND 'z'
    BEGIN
        RETURN ''
    END

    IF      @LastChar = 'z'
    BEGIN
        SELECT  @LastChar = 'a'
        IF      @Remainder = ''
            SELECT  @Remainder = 'a'
        ELSE
            SELECT  @Remainder = dbo.IncrementString( @Remainder )
    END
    ELSE
    BEGIN
        SELECT  @LastChar = CHAR( 97 + (ASCII( @LastChar ) - 96) )
    END

    RETURN  @Remainder + @LastChar
END
GO

例如,以下内容将显示从azzz的所有序列:

DECLARE @Chars varchar(10)
SET @Chars = 'a'

WHILE   @Chars <> 'aaaa'
BEGIN
    PRINT   @Chars
    SELECT  @Chars = dbo.IncrementString( @Chars )
END

答案 1 :(得分:0)

有趣的问题,请尝试使用以下脚本,我相信这会对您有所帮助。

    Declare @Input AS VARCHAR(10)='AZZZZ'
    DECLARE @Len AS INT
    SELECT @Len=LEN(@Input)

    ;WITH CTE
    AS
    (
    SELECT SUBSTRING(@Input, @Len, 1) Alphabet
            ,CASE 
            WHEN ASCII(SUBSTRING(@Input, @Len, 1))-64 < 26 THEN CHAR(ASCII(SUBSTRING(@Input, @Len, 1))+1)
            ELSE 'A' END AS New
           ,CASE 
            WHEN ASCII(SUBSTRING(@Input, @Len, 1))-64 < 26 THEN 0
            ELSE 1 END AS iscarryForward        
            ,@Len Number
    UNION ALL
    SELECT SUBSTRING(@Input, Number-1, 1) Alphabet
           ,CASE 
            WHEN iscarryForward=1 AND ASCII(SUBSTRING(@Input, Number-1, 1))-64 < 26 THEN CHAR(ASCII(SUBSTRING(@Input, Number-1, 1))+1)
            WHEN iscarryForward=0 THEN SUBSTRING(@Input, Number-1, 1) 
            ELSE 'A' END AS New
           ,CASE 
            WHEN ASCII(SUBSTRING(@Input, Number-1, 1))-64 < 26 THEN 0
            ELSE 1 END AS iscarryForward        
            ,Number-1 Number
            FROM CTE WHERE Number > 1   

    )
    SELECT 
    * FROM CTE 
    UNION ALL
    SELECT '' Alphabet,'A' New ,0 iscarryForward,0 Number  FROM CTE 
           HAVING SUM(iscarryForward)=@Len  

请完成此操作并立即根据您的要求进行更改..