The UNICODE()
function in SQL Server is used to return the integer Unicode value for the first character of a specified string. This value corresponds to the Unicode code point of the character.
Syntax
UNICODE(string_expression)
Parameters
- string_expression: A string (of type
nchar
,nvarchar
, orntext
) from which the Unicode value of the first character is returned.
Return Value
- Returns an integer representing the Unicode code point of the first character in the string.
- If the input is an empty string, the function returns
NULL
.
Example Usage
1. Basic Example
SELECT UNICODE('A') AS UnicodeValue; -- Returns 65
SELECT UNICODE('Ω') AS UnicodeValue; -- Returns 937
SELECT UNICODE('🙂') AS UnicodeValue; -- Returns 9786 (if supported)
2. Handling Multicharacter Strings
The function evaluates only the first character.
SELECT UNICODE('Hello') AS UnicodeValue; -- Returns 72 (Unicode for 'H')
3. Empty String or NULL
SELECT UNICODE('') AS UnicodeValue; -- Returns NULL
SELECT UNICODE(NULL) AS UnicodeValue; -- Returns NULL
4. Working with Unicode Characters
SELECT UNICODE(N'you') AS UnicodeValue; -- Returns 20320
SELECT UNICODE(N'Character') AS UnicodeValue; -- Returns 23383
Notes
- Use
N'
prefix for Unicode strings to ensure proper handling. - For reverse operation (getting the character from a Unicode code point), use the
NCHAR()
function:
SELECT NCHAR(65) AS Character; -- Returns 'A'
This function is particularly useful for applications where Unicode handling is necessary, such as internationalized text processing.
No comments:
Post a Comment