Home » SQL TRANSLATE()

SQL TRANSLATE()

The SQL TRANSLATE() is a string function that is used to replaces a sequence of characters in a string with another sequence of characters.





The function replaces a single character at a time. Until SQL Server 2016, you must have used  REPLACE() function to replace each character.

SYNTAX

TRANSLATE (inputstring, from_text, to_text)

Inputstring  is any input string.

from_text is a characters that should be replaced from input string.

to_text is a new characters.

from_text and to_text should have same length.  If the lengths of from_text and to_text are different, the TRANSLATE function will return an error.

Lets look at an example of TRANSLATE function in SQL.

Using TRANSLATE Function to replace characters in string

Following statement uses Translate function and replace the * with and ) with ! in string ‘Hello*world)’

DECLARE @string AS VARCHAR(50)= 'Hello*World)'

SELECT @string AS String, TRANSLATE(@string,'*)','-!') AS ReplacedString

 

TRANSLATE Function VS REPLACE Function

Here we have a string ‘1{2}3@5’, Lets replace curly braces { and } with and +, and @ with * within string using Replace and Tranaslate function.

DECLARE @string AS VARCHAR(50)= '1{2}3@5'

SELECT @string AS String,
REPLACE(REPLACE(REPLACE(@string,'{', '-'), '}', '+'), '@', '*') AS UsingReplaceFn,
TRANSLATE(@string,'{}@','-+*') AS UsingTranslateFn

As you can see, Replace and Translate functions replace the characters within string in desired format.




SQL Server String Functions

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.