0

Probably a simple one but I'm having trouble getting this to work in SQL. ( easy with VBA ).

Given xxx_123_abcd I need to extract the 123 part. whatever code searchs for the _ should always work from the left because sometimes and string might be xxx_123_abcd_xxx.

Thanks in advance for any advice :)

6
  • 4
    This is not very well explained. Can you elaborate on exactly what you need? Commented Jun 17, 2014 at 8:05
  • My advice is: Avoid strings like 'xxx_123_abcd_xxx' in an rdbms, if you are interested in the substrings. Have four columns instead: 'xxx', '123', 'abcd', 'xxx'. As to string manipulation: What do you want to extract? The first integer? The second substring? Commented Jun 17, 2014 at 8:10
  • The number is always 123? The Length is always 3 digits? Commented Jun 17, 2014 at 8:33
  • possible duplicate of How to get a substring '403162' from the given string 'Praveen(403162)' in sql? Commented Jun 17, 2014 at 8:33
  • will the 123 part always be 3 digits? Commented Jun 17, 2014 at 8:38

4 Answers 4

1

Use CHARINDEX to search for the underscores, to be able to extract the part of the string you need with SUBSTRING. Something like this should work:

SELECT
    SUBSTRING(MyColumn, CHARINDEX('_', MyColumn)+1,
        CHARINDEX('_', MyColumn, CHARINDEX('_', MyColumn)+1)-CHARINDEX('_', MyColumn)-1)
FROM
    MyTable

MyColumn = xxx_123_abcd_xxx produces 123 using the above code.

Assumptions: The string you are looking for is enclosed by the first and second occurence of an underscore.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. To all, i should have specified that the return value i was looking for could be two didgits
1

Assumptions

  1. The numeric string you are searching for is always three digits
  2. It is always preceded by an '_'
  3. It immediately follows the first occurrence of '_' in the string

Then this will work

SELECT SUBSTRING('xxx_123_abcd',CHARINDEX('_','xxx_123_abcd')+1,3)

Comments

1

you can also go with this

SELECT LEFT(Col1,PATINDEX('%[^0-9]%', Col1+'a')-1) from(
    SELECT SUBSTRING(Col1, PATINDEX('%[0-9]%', Col1), LEN(Col1)) As Result From table
)x

Comments

1

Use a custom Split function such as described here.

If the xxx_123 part is always the same length, you could also use

SUBSTRING('xxx_123_abcd',5,7)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.