0

I want to extract the string after the second _ character and also remove the (C) in a Microsoft SQL Server Query.

The field name is Asset Code

Table name is dbo.DynamicsMOJ Data

Data Examples:

Values for Asset Code

CP04K_54560_633331 (C)
CP04K_54560_641121 (C)
ME030_72159_690940 (C)
HB21M_60966_1181492 (C)
AW000_1144713 (C)

And so forth, all the values in this field are of similar format however some only have a single "_"

I need to get

'633331'
'641121'
'690940'
'1181492'
'1144713'

1 Answer 1

1

My variants:

SELECT
  txt,
  CHARINDEX('_',REVERSE(txt)), -- there is 0 for four last examples
  --REPLACE(RIGHT(txt,ISNULL(NULLIF(CHARINDEX('_',REVERSE(txt))-1,-1),LEN(txt))),' (C)','')
  -- the next variants is better if we have different count of spaces before '(C)'
  RTRIM(REPLACE(RIGHT(txt,ISNULL(NULLIF(CHARINDEX('_',REVERSE(txt))-1,-1),LEN(txt))),'(C)','')),
  RTRIM(REPLACE(IIF(CHARINDEX('_',txt)=0,txt,RIGHT(txt,CHARINDEX('_',REVERSE(txt))-1)),'(C)',''))
FROM
  (VALUES
    ('CP04K_54560_633331 (C)'),
    ('CP04K_54560_641121 (C)'),
    ('ME030_72159_690940 (C)'),
    ('HB21M_60966_1181492 (C)'),
    ('AW000_1144713 (C)'),
    (NULL),
    (''),
    ('1234567(C)'),
    ('1234567       (C)'),
    ('1234567')
  ) v(txt)

You can check your data using the following query:

SELECT *
FROM
  (VALUES
    ('CP04K_54560_633331 (C)'),
    ('CP04K_54560_641121 (C)'),
    ('ME030_72159_690940 (C)'),
    ('HB21M_60966_1181492 (C)'),
    ('AW000_1144713 (C)'),
    (NULL),
    (''),
    ('1234567(C)'),
    ('1234567       (C)'),
    ('1234567')
  ) v(txt)
WHERE CHARINDEX('_',txt)=0

I think it will get you all the values without '_'.

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

4 Comments

I wanted to extract the string in the whole Asset Code field which has over 200,000 lines. I tried changing FROM (VALUES ('CP04K_54560_633331 (C)'), ('CP04K_54560_641121 (C)'), ('ME030_72159_690940 (C)'), ('HB21M_60966_1181492 (C)'), ('AW000_1144713 (C)') ) v(txt) To FROM dbo.DynamicsMOJ Data Is there anything else that I would need to change in the query to get this to work properly?
No, it's enough - SELECT ... FROM dbo.DynamicsMOJ. And to replace txt into your column name.
When I enter that SQL Query it comes up with an error "Msg 536, Level 16, State 2, Line 1 Invalid length parameter passed to the RIGHT function."
@Matthew - I've added several examples and modified the query for specific cases.

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.