Here, I am going to explain some basics of UNICODE data types and functions in SQL Server. UNICODE is a uniform character encoding standard. A UNICODE character uses multiple bytes to store the data in the database. This means that using UNICODE it is possible to process characters of various writing systems in one document. This could be useful if you're working with an international character set (for example different languages). So let's have a look at a practical example of how to use UNICODE data types and functions in SQL Server 2012. The example is developed in SQL Server 2012 using the SQL Server Management Studio.
SQL Server supports three UNICODE data types; they are:
- NCHAR
- NVARCHAR
- NTEXT
NCHAR
The NCHAR data type specifies the string length and must be a value from 1 through 4,000. The NCHAR data type stores fixed length UNICODE characters. It should be used for the definition of alphanumeric columns, where all data values are approximately the same length.
Example
DECLARE @Ncharlength NCHAR(4001)
Select @Ncharlength
Output
NVARCHAR
The NVARCHAR data type can also store 4000 characters. The NVARCHAR data type stores UNICODE characters of varying length. It should be used for the definition of alphanumeric columns, where the values vary dramatically in size.
NTEXT
The ISO synonym for "ntext" is "national text". NTEXT stores large character data (with more than 4000 characters).
UNICODE Functions in SQL Server
There are two functions related to UNICODE.
- Unicode('char_expression')
- Nchar(int_expression)
UNICODE Function
The UNICODE function works just like ASCII, except it accepts the UNICODE character value as input. This could be useful if you're working with international character sets. The function UNICODE returns the integer value for the first character of the UNICODE character string char_expression.
Syntax
UNICODE('ncharacter_expression')
Example
DECLARE @Name nchar(12)
SET @Name = N'Rohatash'
SELECT UNICODE(@Name) As FirstCharacterUnicodeValue
Go
SELECT UNICODE('G') AS [Unicode Value of G], UNICODE('R') AS [Unicode Value of R], UNICODE('A') AS [Unicode Value of A],
UNICODE('d') AS [Unicode Value of d], UNICODE('D') AS [Unicode Value of D],UNICODE('+') AS [Unicode Value of +]
Output
NCHAR Function
The function Nchar returns the UNICODE character for the integer value int_expression. The NCHAR function works exactly like CHAR except it returns the UNICODE character. This function is useful if you're working with large international character sets.
Syntax
NCHAR(integer_expression)
Example
Output
Declare @name nvarchar(40)
Set @name= 'Rohatash'
Select UNICODE (@name) as Integervalue, NCHAR (unicode(@name)) as 'Unicode'
Output