SQL UNICODE Function

The SQL UNICODE function is a SQL String Function which returns 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

SELECT UNICODE (NCharacter_Expression)
FROM [Source]

Character_Expression: Please specify the valid Expression for which you want to find the UNICODE value. UNICODE 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 1

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 UNICODE Function example, Below lines of 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, we are finding the UNICODE value of è and integer 5.

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

In the next line, We used the SQL UNICODE function directly on a group of Ncharacters (word). Here, UNICODE function 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 the UNICODE function 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;

SQL UNICODE Function Example 2

In this example, We are going to use the SQL UNICODE function inside the WHILE LOOP. I suggest you refer both the SUBSTRING and WHILE LOOP articles in 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