Sometime last year I posted some examples of string functions in SQL and Powershell. Today I am posting about the REVERSE function. The REVERSE function returns the reverse order of a string value. Just like most functions the syntax is straightforward, but when combined with other string functions can be very powerful.

[code langauge=“sql”] REVERSE ( string)


This example reverse the characters in a variable:

sql

DECLARE @myvar varchar(10) SET @myvar = ‘sdrawroF’ SELECT REVERSE(@myvar) AS Reversed ; GO


Using REVERSE and CHARINDEX together implements a LastIndexOf string function. The examples below reverses the variable so that only the number at the end of the function is returned.

sql

DECLARE @myvar varchar(64) SET @myvar = ‘Now_IsTheTime_ForAllGoodMen39554527’ SELECT reverse( cast (substring (reverse(@myvar), 1, charindex ( ‘’,reverse (@myvar))-1) as int )) AS Reversed ; GO

DECLARE @myvar varchar(64) SET @myvar = ‘Now_IsTheTime_ForAllGoodMen_ToGoToTheParty394527’ SELECT reverse( cast (substring (reverse(@myvar), 1, charindex ( ‘’,reverse (@myvar))-1) as int )) AS Reversed ; GO

```

This post has several other uses of REVERSE.