Monday, 18 January 2016

SQL: String Function - Reverse

To get the filename of a fully-qualified path

declare @filename varchar(255) = '\\data\share\IT\yes\Myfile.csv'

select
substring(reverse(@filename),1,charindex('\',reverse(@filename)) ) 'Reverse',
reverse(substring(reverse(@filename),1,charindex('\',reverse(@filename)) ) ) 'Filename with slash',
reverse(substring(reverse(@filename),1,charindex('\',reverse(@filename)) -1 ) ) 'Filename',
substring(@filename,1,charindex(reverse(substring(reverse(@filename),1,charindex('\',reverse(@filename)) ) ),@filename)) 'Path',
SUBSTRING(@filename,1,LEN(@filename)-(CHARINDEX('\',REVERSE(@filename))-1)) AS SamePath