Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse characters in string with mixed Left-to-right and Right-to-left languages using SQL?

I have string values in my table which includes Hebrew characters (or any R-T-L language for this case) and English ones (or numbers).

The problem is that the English characters are reversed and looks like: בדיקה 123456 esrever sti fI kcehC. The numbers and the English characters are reversed, the Hebrew ones are fine.

How can I use built in SQL functions to identify the English substring (and the numbers) and reverse it while maintain the order on the other RTL characters? Any workaround will do :-) ... thanks

like image 880
Nadav Oz Avatar asked Dec 14 '15 13:12

Nadav Oz


People also ask

How do I reverse a string in SQL?

SQL Server REVERSE() Function The REVERSE() function reverses a string and returns the result.

How do I reverse the order of data in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I reverse first and last name in SQL?

Use the REVERSE() function (available since SQL Server 2008). It does what it implies! Always reverse the string because the last name is often only 1 combination and first names can be many.


1 Answers

I believe that your entire string is reversed and the fact that the Hebrew words are displaying in the correct order is actually the result of a different problem. What I suspect is that the Hebrew words are stored in a non-lexical order.

In theory you should be able to resolve your problem by simply reversing the string and then force SQL Server to display the Arabic words from left to right. This is done by appending a special character to the front and back of your string as follow:

    DECLARE @sourceString NVARCHAR(100) = N'123456 בדיקה esrever sti fI kcehC';

    DECLARE @reversedString NVARCHAR(4000)  = nchar(8237) + REVERSE(@sourceString) +  nchar(8236)

    SELECT @reversedString;
like image 69
Edmond Quinton Avatar answered Oct 09 '22 10:10

Edmond Quinton