Converting Your Text from Latin to Cyrillic

Create a function that converts characters from Latin to Cyrillic in SQL Server

Imagine you have text which is written in Latin characters but you need them to be in Cyrillic characters. What will you do? Are you going to write that again from the beginning with Cyrillic characters? Of course not. Why lose all that precious time by typing again?

In this article I am going to show you how to create a scalar function that will convert your Latin characters into Cyrillic characters (Unicode). In this example I will convert from Latin to Cyrillic characters. You can use this function inside of your application as well if your application uses Microsoft SQL Server.

The process of creating the function that converts characters from Latin to Cyrillic is the following,

First of all we need two variables where we are going to store all characters for both Latin and Cyrillic. There will be some other variables as well for character, position and so on. After that we are going to create a WHILE loop and check every character and convert that character to Cyrillic.

You will have a better understanding once you take a look at the code snippet below,

  1. CREATE FUNCTION [dbo].[to_cyrillic] (@src varchar(4000))  
  2. RETURNS nvarchar(4000) AS  
  3. BEGIN  
  4. DECLARE @latin nvarchar(100)  
  5. DECLARE @cyrillic nvarchar(100)  
  6. DECLARE @i int  
  7. DECLARE @character nvarchar(1)  
  8. DECLARE @position int  
  9. DECLARE @dest nvarchar(1000)  
  10.   
  11. SET @src = UPPER(@src);  
  12. SET @latin = 'abvgd|e`zyijklqmnwoprst}ufhc~x{ABVGD\E@ZYIJKLQMNWOPRST]UFHC^X[';  
  13. SET @cyrillic =   
  14. -- All Cyrillic characters are shown as "???" (C-sharpcorner is not showing Cyrillic characters)  
  15. SET @dest = '';  
  16. SET @i = 1;  
  17.   
  18. WHILE (@i <= LEN(@src))  
  19. BEGIN  
  20. SET @character = SUBSTRING(@src, @i, 1)  
  21. SET @position = CHARINDEX(@character, @latin)  
  22. IF (@position = 0) SET @dest = @dest + @character ELSE  
  23. BEGIN  
  24. IF ((ASCII(@character) < 96) AND (@position<32))  
  25. SET @dest = @dest + SUBSTRING(@cyrillic, @position+31, 1)  
  26. ELSE SET @dest = @dest + SUBSTRING(@cyrillic, @position, 1)  
  27. END  
  28. SET @i = @i + 1  
  29. END  
  30. RETURN @dest  
  31. END  
Using the function above

To use the function you just need to use it in your SELECT statement. For example I am going to convert my name from Latin to Cyrillic characters.
  1. select [dbo].[to_cyrillic]('BARLET'AS [Cyrillic characters]  
When I run the query above I see that my name ‘BARLET’ is converted to ‘??????’. You can see the result in the picture below.