Home Forums SQL Server 2005 T-SQL (SS2K5) Find last occurence of a character within a string RE: Find last occurence of a character within a string

  • Quickest way is to reverse the string and look for the first occurrence.

    DECLARE @StringA varchar(100), @pos int

    SET @stringA = 'DirectoryA\DirectoryB\FileName'

    -- Where is the last '\'?

    SET @pos = LEN(@StringA) - CHARINDEX('\',REVERSE(@StringA))

    SELECT @pos

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass