T-SQL Substring - Last 3 Characters

前端 未结 5 383
野趣味
野趣味 2021-01-31 07:01

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?

So the column text is IDS_ENUM_Change_262147_190

5条回答
  •  被撕碎了的回忆
    2021-01-31 07:29

    declare @newdata varchar(30)
    set @newdata='IDS_ENUM_Change_262147_190'
    select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))
    

    === Explanation ===

    I found it easier to read written like this:

    SELECT
        REVERSE( --4.
            SUBSTRING( -- 3.
                REVERSE(),
                0,
                CHARINDEX( -- 2.
                    '',
                    REVERSE() -- 1.
                )
            )
        )
    FROM
        
    
    1. Reverse the text
    2. Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
    3. Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
    4. Reversed the reversed string to give you your desired substring

提交回复
热议问题