SQL Reverse String Function

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.

REVERSE ( string)

This example reverse the characters in a variable:


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.


DECLARE @myvar varchar(64)
SET @myvar = 'Now_IsTheTime_ForAllGoodMen_39554527'
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_ToGoToTheParty_394527'
SELECT reverse( cast (substring (reverse(@myvar), 1, charindex ( '_',reverse (@myvar))-1) as int )) AS Reversed ;
GO

This post has several other uses of REVERSE.

Author: Richie Lee

Full time computer guy, part time runner. Full time Dad, part time blogger. Pokémon Nut. Writer of fractured sentences. Maker of the best damn macaroni cheese you've ever tasted.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s