SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

Reverse It

Recently I had a conversation with a colleague that wasn’t aware of the REVERSE function in SQL Server.  I had sent them a code snippet and they inquired as to what the purpose of the function was.  Essentially, this function that reverses any string value.

For example, the phrase:

The brown dog jumped over the lazy fox

reversed looks like this

xof yzal eht revo depmuj god nworb ehT

Or in Management Studio

Awesome.  Where can I use this?  I use this function when I need to get file names for data or log files of a database.  These are the steps to do this:

  1. Reverse the full path of the file name
  2. Use the LEFT function to return all of the characters left of the first instance of “\”
  3. Reverse the string back to normal orientation
SELECT  name AS 'Database Name' ,
        REVERSE(physical_name) 'Path Reversed' ,
        REVERSE(LEFT(REVERSE(physical_name),
                     CHARINDEX('\', REVERSE(physical_name)) - 1)) AS 'File Name'
FROM    sys.master_files;

In Management Studio,

Voilá!!  We have the file names.  This is also helpful whenever you need to find the tail end of a string that has some type of delimiter.

Enjoy!

© 2017, John Morehouse. All rights reserved.

John Morehouse | Sqlrus.com

John Morehouse is currently a Database Architect with Farm Credit Mid-America out of Louisville, KY. He is a blogger, avid tweeter, and a frequent speaker at SQL Saturday's as well as other conferences. He is also heavily involved with the Professional Association of SQL Server (PASS). In his spare time, you can usually find John reading up on SQL Server topics as well as chasing his two boys around the house.

Comments

Leave a comment on the original post [sqlrus.com, opens in a new window]

Loading comments...