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

In SQL Server, you can use the T-SQL NCHAR() function to return the Unicode character based on the specified integer code.

You provide the integer code as an argument, and the function will return the Unicode character as defined by the Unicode standard.

Syntax

The syntax goes like this:

NCHAR ( integer_expression )

Where integer_expression is the integer for which you want the Unicode character returned.

Example 1 – Basic Usage

Here’s a basic example to demonstrate:

SELECT NCHAR(123) AS Result;

Result:

+----------+
| Result   |
|----------|
| {        |
+----------+

Example 2 – Out of Range

The Microsoft documentation states the following about the range of acceptable integers:

When the collation of the database does not contain the Supplementary Character (SC) flag, this is a positive integer from 0 through 65535 (0 through 0xFFFF). If a value outside this range is specified, NULL is returned. For more information about supplementary characters, see Collation and Unicode Support.

When the collation of the database supports the SC flag, this is a positive integer from 0 through 1114111 (0 through 0x10FFFF). If a value outside this range is specified, NULL is returned.

Here’s an example of what happens if we go outside the range of the collation of the database.

SELECT NCHAR(65536) AS Result;

Result:

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

In this case, the database does not contain the Supplementary Character (SC) flag, and therefore 65536 is out of range, and NULL is returned for that value.

Return Types

It’s also worth noting that the return type of this function is nchar(1) when the default database doesn’t support supplementary characters, and nvarchar(2) when it does.