SQL Server String NCHAR() Function


SQL Server NCHAR() Function

The SQL Server NCHAR() function is used to return the Unicode character that corresponds to the specified integer code. This function is useful for working with Unicode data and characters.


Syntax

SELECT NCHAR(integer_expression);

The NCHAR() function takes a single argument:

  • integer_expression: The integer code of the Unicode character to be returned.

Example SQL Server NCHAR() Function Queries

Let's look at some examples of SQL Server NCHAR() function queries:

1. Basic NCHAR() Example

SELECT NCHAR(65) AS unicode_character;

This query returns the Unicode character that corresponds to the integer code 65. The result will be:

unicode_character
-----------------
A

2. NCHAR() with a Column

SELECT employee_id, NCHAR(salary_grade) AS grade_character
FROM employees;

This query converts the integer values in the salary_grade column to their corresponding Unicode characters for each employee. The result will show the employee_id and the Unicode character as grade_character.

3. NCHAR() with a Variable

DECLARE @unicodeCode INT;
SET @unicodeCode = 66;
SELECT NCHAR(@unicodeCode) AS unicode_character;

This query uses a variable to store an integer code and then converts it to its corresponding Unicode character. The result will be:

unicode_character
-----------------
B

Full Example

Let's go through a complete example that includes creating a table, inserting data, and using the NCHAR() function.

Step 1: Creating a Table

This step involves creating a new table named example_table to store some sample data.

CREATE TABLE example_table (
    id INT PRIMARY KEY,
    unicode_code INT
);

In this example, we create a table named example_table with columns for id and unicode_code.

Step 2: Inserting Data into the Table

This step involves inserting some sample data into the example_table.

INSERT INTO example_table (id, unicode_code) VALUES (1, 65);
INSERT INTO example_table (id, unicode_code) VALUES (2, 66);
INSERT INTO example_table (id, unicode_code) VALUES (3, 67);

Here, we insert data into the example_table.

Step 3: Using the NCHAR() Function

This step involves using the NCHAR() function to convert the integer codes in the unicode_code column to their corresponding Unicode characters.

SELECT id, unicode_code, NCHAR(unicode_code) AS unicode_character
FROM example_table;

This query retrieves the id, unicode_code, and the Unicode character corresponding to the unicode_code for each row in the example_table. The result will be:

id  unicode_code  unicode_character
--- ------------- -----------------
1   65            A
2   66            B
3   67            C

Conclusion

The SQL Server NCHAR() function is a powerful tool for converting integer codes to their corresponding Unicode characters. Understanding how to use the NCHAR() function and its syntax is essential for effective string manipulation and data processing in SQL Server.