Summary: in this tutorial, you will learn how to use the SQL Server ASCII()
function to get the ASCII code of a character.
SQL Server ASCII() function overview
The ASCII()
function accepts a character expression and returns the ASCII code value of the leftmost character of the character expression.
The following shows the syntax of the ASCII()
function:
ASCII ( input_string )
Code language: SQL (Structured Query Language) (sql)
In this syntax, the input_string
can be a literal character, a character string expression, or a table column.
If the input_string
has more than one character, the function returns the ASCII code value of its leftmost character.
The ASCII stands for American Standard Code for Information Interchange. ASCII is used as a character encoding standard for modern computers.
SQL Server ASCII() function examples
Let’s take some examples of using the ASCII()
function.
1) Basic SQL Server ASCII() function
The following example uses the ASCII() function to get the ASCII codes of characters A and Z:
SELECT
ASCII('AB') A,
ASCII('Z') Z;
Code language: SQL (Structured Query Language) (sql)
Here is the output:
A Z
----------- -----------
65 90
(1 row affected)
2) Using ASCII() function with strings
The following example uses the ASCII() function with a string:
SELECT ASCII('Apple') result;
Code language: SQL (Structured Query Language) (sql)
Output:
result
-----------
65
In this example, the input string is Apple. So the ASCII()
function returns the ASCII code of the character A
, which is the leftmost character of the string.
3) Using the ASCII() function in a CTE
The following statement uses the ASCII()
function to generate 26 alphabet characters:
WITH cte AS(
SELECT
CHAR(ASCII('A')) [char],
1 [count]
UNION ALL
SELECT
CHAR(ASCII('A') + cte.count) [char],
cte.count + 1 [count]
FROM
cte
)
SELECT
TOP(26) cte.char
FROM
cte;
Code language: SQL (Structured Query Language) (sql)
Here is the output:
Summary
- Use the
ASCII()
function to get the ASCII code value of a character.