Client wants to append a field with a literal increment based on a count.
The range goes from ‘aa‘ to ‘zz‘.
‘aa‘ represents a count of 1 and ‘zz‘ represents the max value in the range: 676
I have sql that almost works but would appreciate an expert eye to get me over the last hurdle.
--Constants
DECLARE @START_ASCII INT = 97
DECLARE @ASCII_OFFSET INT = 1
DECLARE @ALPHABET_LETTER_COUNT INT = 26
--Variables
DECLARE @RecordCount INT = 0
DECLARE @FirstLetter VARCHAR(1) = NULL
DECLARE @SecondLetter VARCHAR(1) = NULL
SET @RecordCount = 1 --Range is 1 to 676 (e.g. 'aa' to 'zz')
SET @FirstLetter = CHAR(round(@RecordCount / @ALPHABET_LETTER_COUNT, 2, 1) + @START_ASCII)
SET @SecondLetter = CHAR((((@RecordCount - @ASCII_OFFSET) % @ALPHABET_LETTER_COUNT) + @START_ASCII))
SELECT @FirstLetter + @SecondLetter
The problem with the above sql involves the first letter. It works till the end of the alphabet is reached for the second letter. For example, at a count of 26, I expect ‘az‘, but instead get ‘bz‘.
I want to keep the SQL small and tight (e.g. no CASE statements). Is there a small tweak I can make to the above code so that it will work?
Or, if there is just a smarter way to skin this cat, I’d like to know that.
I would think of this as computing the base-26 representation of
@RecordCount-1(range 0 to 675). Then map the two-digits of the base-26 number to the ASCII characters: