简体   繁体   中英

SQL Server : extracting the Midddle Characters without CHARINDEX

To start, I have seen the CHARINDEX results on here but none of them seem to be working for my case. The reasons are either a, CHARINDEX can't help me, or b, I am not understanding how CHARINDEX works. That being said, I would like to ask my question here in hopes that I can get some clarification on both how to solve my issue and CHARINDEX if that so happens to be the way this question is answered.

The variable that I am trying to extract from has varying length. However, two things are always constant.

  1. There is always a '/' as the 16th character in the string
  2. The last character in the string is always '0' OR '1'

What I am trying to do is extract the name from between '/' and '0' or '1'. In short, I want to chop off the first 16 characters and the last character of every string. So far, this is what I have:

SELECT 
    SUBSTRING([string_name], 17, LEN([string_name]) - 1) AS 'username'
FROM
    [table_name]

The results I get still contain the 0 OR 1 at the end. What I need to do is somehow remove that 0 from the string. It is important to note that the number of characters between '/' and '0' are always different.

Current results:

gordon0
grant0
greg0
guy1
hanying0

Desired results:

gordon
grant
greg
guy
hanying

Any advice here would be wonderful.

Please let me know if you need any additional information from me. If possible, would like to maintain using either SUBSTRING , LEFT or RIGHT .

Thanks

Adjusting the length would seem to address your problem:

SELECT SUBSTRING([string_name], 17, LEN([string_name])-17) AS username
FROM [table_name]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM