SQL UNICODE Function

The SQL UNICODE function is one of the String Functions that return the integer value, as defined in Unicode standards. If we specify the character string (more than one character), then the UNICODE function will return the integer value for the leftmost character of a character expression.

The syntax of the SQL Server UNICODE Function is as shown below.

SELECT UNICODE (NCharacter_Expression)
FROM [Source]

Character_Expression: Please specify the valid Expression for which you want to find the UNICODE value. This Function will return the integer value, as defined in Unicode standards of the leftmost character of this expression. This Character_Expression is of type NChar or NVarchar.

SQL UNICODE Function Example

The UNICODE function returns the Unicode value of the leftmost character of the given expression. The following query may show you multiple ways to use this function.

DECLARE @x NCHAR(25)
DECLARE @y INT

-- Initialize the variables.  
SET @x = 'è'
SET @y = 5

SELECT UNICODE(@x) AS Result1,
       UNICODE(@y) AS Result2 ;

SELECT UNICODE('âëxyz') AS Result3;  

SELECT UNICODE('Å238') AS Result4;
SQL UNICODE Function 1

Within this example, the first four lines of the below code are used to declare two variables of type NCHAR and Integer type. Next, we were assigning the string data è, and 5.

DECLARE @x NCHAR(25)
DECLARE @y INT

-- Initialize the variables.  
SET @x = 'è'
SET @y = 5

From the below statement, you can see that we are finding the UNICODE value of è and integer 5.

SELECT UNICODE(@x) AS Result1,
       UNICODE(@y) AS Result2 ;

In the following line, We used the SQL UNICODE function directly on a group of N characters (word). Here, it will return the Unicode value of the leftmost character (i.e., â), and that should be 226

SELECT UNICODE('âëxyz') AS Result3;

As you can see from the below statement, We used it directly on the combination of NChars and integers. Here, this String Function will return the Unicode value of the leftmost character (i.e., Å), and that should be 197

SELECT UNICODE('Å238') AS Result4;

Example 2

In this example, We are going to use the SQL UNICODE function inside the WHILE LOOP. I suggest you refer to both the SUBSTRING and WHILE LOOP articles in the SQL Server to understand the query execution.

DECLARE @i INT, 
        @str NCHAR(16);  

-- Initialize the variables.  
SET @i = 1;  
SET @str = 'TùtÓrïål GãtÊwáy';
 
WHILE @i <= LEN(@str)
	BEGIN
		SELECT SUBSTRING(@str, @i, 1) AS [NChar_Value],
			   UNICODE(SUBSTRING(@str, @i, 1)) AS [UNICODE_Result]
		SET @i = @i + 1
	END;
SQL UNICODE Function 2