SQL Server CHAR() Function

Summary: in this tutorial, you will learn how to use the SQL Server CHAR() function to convert an ASCII code value to a character.

SQL Server CHAR() function overview

The CHAR() function allows you to convert an ASCII code value to a character value.

Here’s the syntax of the CHAR() function:

CHAR ( code ) Code language: SQL (Structured Query Language) (sql)

In this syntax, the code is an integer expression that evaluates to an integer whose value is from 0 to 255.

If an code evaluates to an integer that is outside of the valid range, the CHAR() function returns NULL. Additionally, the CHAR() function will return NULL if the code is NULL.

The CHAR() function returns a character whose data type is CHAR(1).

Note that to convert a character to an ASCII value, you use the ASCII() function

SQL Server CHAR() function examples

The following example uses the CHAR() function to get the characters of the numbers 65 and 90:

SELECT 
    CHAR(65) char_65, 
    CHAR(90) char_90;Code language: SQL (Structured Query Language) (sql)

Here is the output:

char_65 char_90
------- -------
A       Z

(1 row affected)

The following statement returns NULL because the argument is out of the range from 0 through 255:

SELECT 
    CHAR(1000) out_of_range;Code language: SQL (Structured Query Language) (sql)

The following shows the output:

out_of_range
------------
NULL

(1 row affected)Code language: PHP (php)

The following example uses the CHAR() function to concat two strings. However, the second string is placed in the new line:

SELECT 'Hello,' + CHAR(10) + 'There' AS Result;Code language: SQL (Structured Query Language) (sql)

Output:

Result
------------
Hello,
There

(1 row affected)

In this example, the CHAR(10) returns the new line character, therefore, the second string is placed in the new line.

Summary

  • Use the SQL Server CHAR() function to get a corresponding character from an ASCII value.
Was this tutorial helpful?