Convert a number to letters

后端 未结 1 608
-上瘾入骨i
-上瘾入骨i 2021-01-07 05:37

Given a number, how do you convert that to letters?

相关标签:
1条回答
  • 2021-01-07 06:20

    You can just translate your existing logic into a t-sql scalar function, like so:

    CREATE FUNCTION dbo.fnColumnNameFromIndex(@i int)
    RETURNS varchar(3)
    AS
    BEGIN
    DECLARE @dividend int, @letters varchar(3), @modulo int
        SET @dividend = @i
        SET @letters = ''
    
        WHILE @dividend > 0
        BEGIN
            SET @modulo = (@dividend - 1) % 26
            SET @letters = CHAR(65 + @modulo) + @letters
            SET @dividend = CONVERT(int, (@dividend - @modulo) / 26 )
        END
    
        RETURN @letters;
    END
    GO
    

    Call it like this:

    SELECT dbo.fnColumnNameFromIndex(2000)

    ...admittedly not set logic, but I don't see this as a set logic problem.

    0 讨论(0)
提交回复
热议问题