1

I have a table XYZ with column FileName which has values as follows:

CCA_Type-PROPOSAL_Id-45845_Test1.txt
CPA_Type-PROPOSAL_Id-490845_Test2.txt

I want to update this column so that it contains only the filename and remove other characters preceeding:

Test1.txt
Test2.txt

Hence I wrote the following:

Update XYZ
set FileName = (select RIGHT(FileName,CHARINDEX('_',REVERSE(FileName),0)-1))

But if a FileName has a value like:

  CCA_Type-PROPOSAL_Id-45845_Test_RR1.txt

My script returns RR1.txt instead of Test_RR1.txt! It finds the last underscore and returns substring from there. How can I change it so that I get the 3rd underscore and return a substring following it!

1
  • Search for test instead ? Commented Aug 25, 2014 at 19:45

2 Answers 2

3

charindex optionally takes a start location. You could chain several together:

select right(FileName, len(FileName) - 
   charindex('_', FileName, 
      charindex('_', FileName, 
         charindex('_', FileName) 
      + 1) 
   + 1))

So you're asking for "The first underscore after (the first underscore after (the first underscore))" - i.e. the third underscore.

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

Comments

1

something like this should work:

declare @table table ( 
  [file_name] [sysname] 
  ); 
declare @pattern [sysname]= N'_test'; 
insert into @table 
            ([file_name]) 
values      (N'CCA_Type-PROPOSAL_Id-45845_Test1.txt'), 
            (N'CPA_Type-PROPOSAL_Id-490845_Test2.txt'), 
            (N'CCA_Type-PROPOSAL_Id-45845_Test_RR1.txt'); 
select [file_name]                                                                         as [file_name] 
       , charindex(@pattern, lower([file_name]))                                           as [character_index_of_pattern]
       , substring([file_name], charindex(@pattern, lower([file_name])), len([file_name])) as [desired_output] 
from   @table; 

3 Comments

Thanks for the reply. I found Blorgbeard's solution easier.
This does assume all filenames start with "test", which may not be the case.
That is correct. All file names do not start with Test.

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.