How the CHAR() Function Works in SQL Server (T-SQL)

In SQL Server, the T-SQL CHAR() function converts an int ASCII code to a character value. In other words, you pass in an integer, and the function interprets it as the code value for a string character and returns the corresponding string character.

Syntax

The syntax goes like this:

CHAR ( integer_expression )

Where integer_expression is an integer from 0 through 255.

If you specify an integer outside this range, the result is NULL. The same is true if you provide an integer that expresses only the first byte of a double-byte character.

Example 1 – Basic Usage

Here’s an example to demonstrate the basic usage:

SELECT CHAR(67) AS 'Result';

Result:

+----------+
| Result   |
|----------|
| C        |
+----------+

So if we change the integer, we get a different character:

SELECT CHAR(255) AS 'Result';

Result:

+----------+
| Result   |
|----------|
| ÿ        |
+----------+

Example 2 – Multiple Integers

This function doesn’t support multiple integers as arguments. If you provide multiple integers, you’ll get an error.

Here’s an example:

SELECT CHAR(67, 255) AS 'Result';

Result:

The char function requires 1 argument(s).

Note that this is in contrast to MySQL’s CHAR() function (which allows you to provide multiple integers).

Example 3 – Out of Range Integers

This function also doesn’t support integers outside the range of 1 to 255. If your argument is outside this range, the result is NULL.

Here’s an example:

SELECT CHAR(256) AS 'Result';

Result:

+----------+
| Result   |
|----------|
| NULL     |
+----------+

This is again in contrast to MySQL’s CHAR() function, which accepts integers larger than 255 (in which case, they’re automatically converted into multiple result bytes).

Example 4 – Inserting Control Characters

Here’s an example of using CHAR(13) to print subsequent characters on a new line:

SELECT 'Homer' + CHAR(13) + '[email protected]' AS 'Name/Email';

Result:

+--------------+
| Name/Email   |
|--------------|
| Homer
[email protected]              |
+--------------+

Here’s what it looks like if we remove the CHAR(13):

SELECT 'Homer' AS 'Name', '[email protected]' AS 'Email';

Result:

+--------+-----------------------+
| Name   | Email                 |
|--------+-----------------------|
| Homer  | [email protected] |
+--------+-----------------------+