The SQL Server UNICODE()
function is used to return the integer value, the Unicode code point, for the first character of a specified string. This function is useful for working with Unicode data and retrieving the code points of characters.
SELECT UNICODE(string);
The UNICODE()
function takes a single argument:
string
: The string whose first character's Unicode code point is to be retrieved.Let's look at some examples of SQL Server UNICODE()
function queries:
SELECT UNICODE('A') AS unicode_value;
This query returns the Unicode code point for the character 'A'. The result will be:
unicode_value
--------------
65
SELECT UNICODE('Hello') AS unicode_value;
This query returns the Unicode code point for the first character in the string 'Hello'. The result will be:
unicode_value
--------------
72
SELECT first_name, UNICODE(first_name) AS unicode_value
FROM employees;
This query returns the Unicode code point for the first character in the first_name
column for each employee. The result will show the first_name
and its corresponding Unicode code point.
DECLARE @myString NVARCHAR(50);
SET @myString = N'SQL Server';
SELECT UNICODE(@myString) AS unicode_value;
This query uses a variable to store a string and then returns the Unicode code point for its first character. The result will be:
unicode_value
--------------
83
Let's go through a complete example that includes creating a table, inserting data, and using the UNICODE()
function.
This step involves creating a new table named example_table
to store some sample data.
CREATE TABLE example_table (
id INT PRIMARY KEY,
description NVARCHAR(50)
);
In this example, we create a table named example_table
with columns for id
and description
.
This step involves inserting some sample data into the example_table
.
INSERT INTO example_table (id, description) VALUES (1, N'Apple');
INSERT INTO example_table (id, description) VALUES (2, N'Banana');
INSERT INTO example_table (id, description) VALUES (3, N'Cherry');
Here, we insert data into the example_table
.
This step involves using the UNICODE()
function to retrieve the Unicode code points of the first characters in the description
column.
SELECT id, description, UNICODE(description) AS unicode_value
FROM example_table;
This query retrieves the id
, description
, and the Unicode code point of the first character in the description
column for each row in the example_table
. The result will be:
id description unicode_value
--- ------------ --------------
1 Apple 65
2 Banana 66
3 Cherry 67
The SQL Server UNICODE()
function is a powerful tool for retrieving the Unicode code point for the first character of a specified string. Understanding how to use the UNICODE()
function and its syntax is essential for effective string manipulation and data processing in SQL Server.