How to Loop From A to Z in T-SQL

Written by brendan mason
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Loop From A to Z in T-SQL
Every upper case and lower case letter of the alphabet has a unique ASCII character code. ( Images)

Microsoft SQL Server uses Transact-SQL (T-SQL) as its primary query language. T-SQL "WHILE" loops allow for repeating a process while incrementing a value or looking for a specific condition before exiting the loop. Looping through numeric values is a simple process; however, an alphabetic loop requires translating letters into their equivalent ASCII character codes and then using the "CHAR()" function to convert them back to letters. The ASCII codes for the upper case letters of the alphabet are values 65 through 90. The lower case alphabet is represented by values 97 through 122.

Skill level:


  1. 1

    Open SQL Server Management Studio.

  2. 2

    Open a new query window.

  3. 3

    Declare an integer variable and set its value to 65 as shown:

    DECLARE @intCharCode INT

    SET @intCharCode = 65

  4. 4

    Type the following "WHILE" statement to output the ASCII character equivalent of the integer code represented by the variable. The loop increments the variable by a value of 1 with each iteration until it reaches 90:

    WHILE NOT (@intCharCode > 90)


    PRINT CHAR(@intCharCode)

    SET @intCharCode = @intCharCode + 1


  5. 5

    Click the execute button to run the query. The output will print the upper case alphabet in the results pane in alphabetic order.

Tips and warnings

  • Use the "ASCII()" function to return the ASCII code for any character.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.